58 lines
1.7 KiB
Go
58 lines
1.7 KiB
Go
package auth
|
|
|
|
import (
|
|
"forge.lightcrystal.systems/nilix/quartzgun/cookie"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
type User struct {
|
|
Name string
|
|
Pass string
|
|
Session string
|
|
LoginTime time.Time
|
|
LastSeen time.Time
|
|
|
|
Data map[string]interface{}
|
|
}
|
|
|
|
type UserStore interface {
|
|
InitiateSession(user string, password string, ttl int) (string, error)
|
|
ValidateUser(user string, sessionId string) (bool, error)
|
|
EndSession(user string) error
|
|
AddUser(user string, password string) error
|
|
DeleteUser(user string) error
|
|
ChangePassword(user string, oldPassword string, newPassword string) error
|
|
GetLastLoginTime(user string) (time.Time, error)
|
|
GetLastTimeSeen(user string) (time.Time, error)
|
|
SetData(user string, key string, value interface{}) error
|
|
GetData(user string, key string) (interface{}, error)
|
|
GrantToken(user, password string, ttl int) (string, error)
|
|
ValidateToken(token string) (bool, error)
|
|
ValidateTokenWithScopes(token string, scopes map[string]string) (bool, error)
|
|
}
|
|
|
|
func Login(user string, password string, userStore UserStore, w http.ResponseWriter, t int) error {
|
|
session, loginErr := userStore.InitiateSession(user, password, t)
|
|
if loginErr == nil {
|
|
cookie.StoreToken("user", user, w, t)
|
|
cookie.StoreToken("session", session, w, t)
|
|
csrfToken := cookie.GenToken(64)
|
|
cookie.StoreToken("csrfToken", csrfToken, w, t)
|
|
userStore.SetData(user, "csrfToken", csrfToken)
|
|
return nil
|
|
}
|
|
return loginErr
|
|
}
|
|
|
|
func Logout(user string, userStore UserStore, w http.ResponseWriter) error {
|
|
logoutErr := userStore.EndSession(user)
|
|
if logoutErr == nil {
|
|
cookie.StoreToken("user", "", w, 0)
|
|
cookie.StoreToken("session", "", w, 0)
|
|
cookie.StoreToken("csrfToken", "", w, 0)
|
|
userStore.SetData(user, "csrfToken", "")
|
|
return nil
|
|
}
|
|
return logoutErr
|
|
}
|