Gisle Aune
5 years ago
5 changed files with 58 additions and 99 deletions
-
33models/session.go
-
53models/sessions/open.go
-
25models/user.go
-
21models/users/login.go
-
25models/users/register.go
@ -1,53 +0,0 @@ |
|||
package sessions |
|||
|
|||
import ( |
|||
"crypto/rand" |
|||
"encoding/binary" |
|||
"strconv" |
|||
"time" |
|||
|
|||
"git.aiterp.net/lucifer/lucifer/models" |
|||
) |
|||
|
|||
func Open(repo models.SessionRepository, user models.User) (models.Session, error) { |
|||
id, err := generateID() |
|||
if err != nil { |
|||
return models.Session{}, err |
|||
} |
|||
|
|||
session := models.Session{ID: id, Expires: time.Now().Add(time.Hour * 72), UserID: user.ID} |
|||
|
|||
err = repo.InsertSession(session) |
|||
if err != nil { |
|||
return models.Session{}, err |
|||
} |
|||
|
|||
return session, nil |
|||
} |
|||
|
|||
func generateID() (string, error) { |
|||
result := "S" |
|||
offset := 0 |
|||
data := make([]byte, 32) |
|||
|
|||
_, err := rand.Read(data) |
|||
if err != nil { |
|||
return "", err |
|||
} |
|||
|
|||
for len(result) < 64 { |
|||
result += strconv.FormatUint(binary.LittleEndian.Uint64(data[offset:]), 36) |
|||
offset += 8 |
|||
|
|||
if offset >= 32 { |
|||
_, err = rand.Read(data) |
|||
if err != nil { |
|||
return "", err |
|||
} |
|||
|
|||
offset = 0 |
|||
} |
|||
} |
|||
|
|||
return result[:64], nil |
|||
} |
@ -1,21 +0,0 @@ |
|||
package users |
|||
|
|||
import ( |
|||
"git.aiterp.net/lucifer/lucifer/models" |
|||
"golang.org/x/crypto/bcrypt" |
|||
) |
|||
|
|||
// Login gets a user and compares the password. It does not open a session.
|
|||
func Login(repo models.UserRepository, name, password string) (models.User, error) { |
|||
user, err := repo.FindUserByName(name) |
|||
if err != nil { |
|||
return models.User{}, err |
|||
} |
|||
|
|||
err = bcrypt.CompareHashAndPassword(user.PassHash, []byte(password)) |
|||
if err != nil { |
|||
return models.User{}, err |
|||
} |
|||
|
|||
return user, nil |
|||
} |
@ -1,25 +0,0 @@ |
|||
package users |
|||
|
|||
import ( |
|||
"git.aiterp.net/lucifer/lucifer/models" |
|||
"golang.org/x/crypto/bcrypt" |
|||
) |
|||
|
|||
// Register registers a user
|
|||
func Register(repo models.UserRepository, name, password string) (models.User, error) { |
|||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) |
|||
if err != nil { |
|||
return models.User{}, err |
|||
} |
|||
|
|||
user := models.User{ID: -1, Name: name, PassHash: hash} |
|||
|
|||
id, err := repo.InsertUser(user) |
|||
if err != nil { |
|||
return models.User{}, err |
|||
} |
|||
|
|||
user.ID = id |
|||
|
|||
return user, nil |
|||
} |
Write
Preview
Loading…
Cancel
Save
Reference in new issue