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.

56 lines
1.2 KiB
Go

package account
import (
"bytes"
"crypto/rand"
"database/sql"
"encoding/base64"
"fmt"
"github.com/pagefaultgames/pokerogue-server/db"
)
type LoginRequest GenericAuthRequest
type LoginResponse GenericAuthResponse
// /account/login - log into account
func Login(request LoginRequest) (LoginResponse, error) {
7 months ago
var response LoginResponse
if !isValidUsername(request.Username) {
7 months ago
return response, fmt.Errorf("invalid username")
}
if len(request.Password) < 6 {
7 months ago
return response, fmt.Errorf("invalid password")
}
key, salt, err := db.FetchAccountKeySaltFromUsername(request.Username)
if err != nil {
if err == sql.ErrNoRows {
7 months ago
return response, fmt.Errorf("account doesn't exist")
}
7 months ago
return response, err
}
if !bytes.Equal(key, deriveArgon2IDKey([]byte(request.Password), salt)) {
7 months ago
return response, fmt.Errorf("password doesn't match")
}
token := make([]byte, TokenSize)
_, err = rand.Read(token)
if err != nil {
7 months ago
return response, fmt.Errorf("failed to generate token: %s", err)
}
err = db.AddAccountSession(request.Username, token)
if err != nil {
7 months ago
return response, fmt.Errorf("failed to add account session")
}
7 months ago
response.Token = base64.StdEncoding.EncodeToString(token)
return response, nil
}