2022-01-04 20:23:25 +00:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
2022-01-08 05:52:37 +00:00
|
|
|
"time"
|
2022-01-11 06:30:20 +00:00
|
|
|
"net/http"
|
|
|
|
"nilfm.cc/git/quartzgun/cookie"
|
2022-01-04 20:23:25 +00:00
|
|
|
)
|
|
|
|
|
2022-01-08 05:52:37 +00:00
|
|
|
type User struct {
|
|
|
|
Name string
|
|
|
|
Pass string
|
|
|
|
Session string
|
|
|
|
LoginTime time.Time
|
|
|
|
LastSeen time.Time
|
|
|
|
|
|
|
|
Data map[string]interface{}
|
|
|
|
}
|
|
|
|
|
2022-01-04 20:23:25 +00:00
|
|
|
type UserStore interface {
|
2022-01-08 05:52:37 +00:00
|
|
|
InitiateSession(user string, password string) (string, error)
|
|
|
|
ValidateUser(user string, sessionId string) (bool, error)
|
2022-01-04 20:23:25 +00:00
|
|
|
EndSession(user string) error
|
2022-01-08 05:52:37 +00:00
|
|
|
AddUser(user string, password string) error
|
|
|
|
DeleteUser(user string) error
|
|
|
|
ChangePassword(user string, oldPassword string, newPassword string) error
|
2022-01-11 06:30:20 +00:00
|
|
|
SetData(user string, key string, value interface{}) error
|
|
|
|
GetData(user string, key string) (interface{}, error)
|
2022-01-04 20:23:25 +00:00
|
|
|
}
|
|
|
|
|
2022-01-11 06:30:20 +00:00
|
|
|
func Login(user string, password string, userStore UserStore, w http.ResponseWriter, t int) error {
|
|
|
|
session, loginErr := userStore.InitiateSession(user, password)
|
|
|
|
if loginErr == nil {
|
|
|
|
cookie.StoreToken("user", user, w, t)
|
|
|
|
cookie.StoreToken("session", session, w, t)
|
|
|
|
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)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return logoutErr
|
2022-01-04 20:23:25 +00:00
|
|
|
}
|