hello world

This commit is contained in:
2022-12-09 10:59:15 -06:00
commit 8ae527683b
13 changed files with 552 additions and 0 deletions

103
storage/api.go Normal file
View File

@@ -0,0 +1,103 @@
package storage
import (
"fmt"
"time"
"git.zomo.dev/zomo/discord-retokenizer/util"
"github.com/go-redis/redis/v9"
"golang.org/x/crypto/bcrypt"
)
func UpdateUsername(username string) {
if username != "" {
client.Set(ctx, "username", username, 0)
}
}
func UpdatePassword(password string) {
if password != "" {
passHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
panic(err)
}
client.Set(ctx, "password", string(passHash), 0)
}
}
func CheckLogin(username string, password string) (bool, string) {
if username == "" || password == "" {
return false, ""
}
user, err := client.Get(ctx, "username").Result()
if err != nil {
panic(err)
}
pass, err := client.Get(ctx, "password").Result()
if err != nil {
panic(err)
}
if user != username {
return false, ""
}
err = bcrypt.CompareHashAndPassword([]byte(pass), []byte(password))
if err != nil {
return false, ""
}
return true, createLoginToken()
}
func createLoginToken() string {
token := util.GeneratePassword(32)
member := redis.Z{
Score: float64(time.Now().Unix() + 4 * 60 * 60),
Member: token,
}
err := client.ZAdd(ctx, "loginTokens", member).Err()
if err != nil {
panic(err)
}
return token
}
func CheckLoginToken(token string) bool {
expired, err := client.ZRangeByScore(ctx, "loginTokens", &redis.ZRangeBy{
Min: "-inf",
Max: fmt.Sprintf("%d", time.Now().Unix()),
}).Result()
if err != nil {
panic(err)
}
for _, e := range expired {
client.ZRem(ctx, "loginTokens", e)
}
current, err := client.ZRangeByScore(ctx, "loginTokens", &redis.ZRangeBy{
Min: fmt.Sprintf("%d", time.Now().Unix()),
Max: "inf",
}).Result()
if err != nil {
panic(err)
}
for _, c := range current {
fmt.Println(c)
if c == token {
return true
}
}
return false
}