You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.2 KiB
Go

package auth
import (
"fmt"
"github.com/aziis98/lupus-lite/database"
"github.com/aziis98/lupus-lite/model"
"github.com/aziis98/lupus-lite/util"
"golang.org/x/crypto/bcrypt"
)
type memAuth struct {
db database.Database
sessions map[string]string
}
func (auth *memAuth) Register(username, password string) error {
passwordBCrypt, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return err
}
return auth.db.CreateUser(model.User{
Username: username,
PasswordBCrypt: passwordBCrypt,
})
}
func (auth *memAuth) Login(username, password string) (string, error) {
user, err := auth.db.GetUser(username)
if err != nil {
return "", err
}
if err := bcrypt.CompareHashAndPassword(user.PasswordBCrypt, []byte(password)); err != nil {
return "", err
}
token := util.GenerateRandomString(16)
auth.sessions[token] = username
return token, nil
}
func (auth *memAuth) UserForSession(token string) (string, error) {
username, ok := auth.sessions[token]
if !ok {
return "", fmt.Errorf(`invalid session token`)
}
return username, nil
}
func (auth *memAuth) GetUser(username string) (model.User, error) {
return auth.db.GetUser(username)
}