Decided that auth/ should be its own thing since it's so important, and the session store can go in common/web.go for now.
parent
3e6156e93c
commit
a2080308ca
@ -0,0 +1,76 @@ |
|||||||
|
package auth |
||||||
|
|
||||||
|
import ( |
||||||
|
"errors" |
||||||
|
"golang.org/x/crypto/bcrypt" |
||||||
|
"log" |
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2" |
||||||
|
_ "github.com/mattn/go-sqlite3" |
||||||
|
sq "github.com/Masterminds/squirrel" |
||||||
|
"github.com/gofiber/fiber/v2/middleware/session" |
||||||
|
|
||||||
|
"MY/webapp/data" |
||||||
|
"MY/webapp/config" |
||||||
|
"MY/webapp/common" |
||||||
|
) |
||||||
|
|
||||||
|
func IsAdmin(user *data.User) bool { |
||||||
|
return user.Username == config.Settings.Admin |
||||||
|
} |
||||||
|
|
||||||
|
func Check(c *fiber.Ctx, needs_admin bool) (*session.Session, error) { |
||||||
|
sess, err := common.STORE.Get(c) |
||||||
|
if err != nil { return sess, err } |
||||||
|
|
||||||
|
// BUG: this has to come from the databse, just temporary
|
||||||
|
admin := sess.Get("admin") == true |
||||||
|
authed := sess.Get("authenticated") == true |
||||||
|
|
||||||
|
if needs_admin { |
||||||
|
authed = admin && authed |
||||||
|
log.Printf("after needs_admin block: authed=%v", authed) |
||||||
|
} |
||||||
|
|
||||||
|
if authed { |
||||||
|
log.Println("user is authed, return nil and sess") |
||||||
|
return sess, nil |
||||||
|
} else { |
||||||
|
log.Println("user is NOT authed, return error") |
||||||
|
return sess, errors.New("Authentication, permission failure") |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
func LogoutUser(c *fiber.Ctx) error { |
||||||
|
sess, err := common.STORE.Get(c) |
||||||
|
if err != nil { return err } |
||||||
|
|
||||||
|
err = sess.Destroy() |
||||||
|
if err != nil { return err } |
||||||
|
|
||||||
|
err = sess.Save() |
||||||
|
return err |
||||||
|
} |
||||||
|
|
||||||
|
func LoginUser(result *data.User, login *data.Login) (bool, error) { |
||||||
|
sql, args, err := sq.Select("username, password"). |
||||||
|
From("user").Where("username=?", login.Username).ToSql() |
||||||
|
|
||||||
|
if err != nil { return false, err } |
||||||
|
|
||||||
|
err = data.DB.Get(result, sql, args...) |
||||||
|
if err != nil { return false, err } |
||||||
|
|
||||||
|
pass_good := bcrypt.CompareHashAndPassword([]byte(result.Password), []byte(login.Password)) |
||||||
|
if pass_good != nil { return false, pass_good } |
||||||
|
|
||||||
|
return login.Username == result.Username && pass_good == nil, nil |
||||||
|
} |
||||||
|
|
||||||
|
func SetUserPassword(user *data.User) error { |
||||||
|
hashed, err := bcrypt.GenerateFromPassword([]byte(user.Password), 12) |
||||||
|
if err != nil { return err } |
||||||
|
|
||||||
|
user.Password = string(hashed) |
||||||
|
return nil |
||||||
|
} |
||||||
Loading…
Reference in new issue