Initial commit
This commit is contained in:
76
pkg/auth/auth.go
Normal file
76
pkg/auth/auth.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"addrss/pkg/repo"
|
||||
"fmt"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type UserLogin struct {
|
||||
EmailAddress string `json:"emailAddress"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func AuthenticateGuest() (Tokens, error) {
|
||||
gt, err := getGuestToken()
|
||||
if err != nil {
|
||||
return Tokens{}, err
|
||||
}
|
||||
return Tokens{AccessToken: gt}, nil
|
||||
}
|
||||
|
||||
func AuthenticateUserLogin(userLogin UserLogin) (Tokens, error) {
|
||||
user, err := repo.GetUserByEmail(userLogin.EmailAddress)
|
||||
if err != nil {
|
||||
return Tokens{}, &ErrorUnauthorized{err}
|
||||
}
|
||||
|
||||
if err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(userLogin.Password)); err != nil {
|
||||
return Tokens{}, &ErrorUnauthorized{err}
|
||||
}
|
||||
|
||||
tokens, err := AcquireTokens(user)
|
||||
if err != nil {
|
||||
return Tokens{}, &ErrorForbidden{err}
|
||||
}
|
||||
|
||||
return tokens, nil
|
||||
}
|
||||
|
||||
func AuthenticateUserRefresh(refreshToken string) (Tokens, error) {
|
||||
claims := RefreshClaims{}
|
||||
if err := ValidateJwtToken(refreshToken, &claims); err != nil {
|
||||
return Tokens{}, &ErrorUnauthorized{err}
|
||||
}
|
||||
|
||||
us, err := repo.GetUserSessionById(claims.Sub)
|
||||
if err != nil {
|
||||
return Tokens{}, &ErrorUnauthorized{err}
|
||||
}
|
||||
|
||||
if us.TokenId != claims.Jti {
|
||||
_ = repo.DeleteUserSession(claims.Sub)
|
||||
return Tokens{}, &ErrorUnauthorized{fmt.Errorf("token id mismatch")}
|
||||
}
|
||||
|
||||
user, err := repo.GetUserById(claims.Sub)
|
||||
if err != nil {
|
||||
return Tokens{}, &ErrorUnauthorized{err}
|
||||
}
|
||||
|
||||
tokens, err := AcquireTokens(user)
|
||||
if err != nil {
|
||||
return Tokens{}, &ErrorForbidden{err}
|
||||
}
|
||||
|
||||
return tokens, nil
|
||||
}
|
||||
|
||||
func DestroySession(userId int64) error {
|
||||
if err := repo.DeleteUserSession(userId); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user