usermanager.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. package usermanager
  2. import (
  3. "errors"
  4. "time"
  5. "strconv"
  6. "git.mmnx.de/Moe/databaseutils"
  7. "git.mmnx.de/Moe/configutils"
  8. "github.com/dgrijalva/jwt-go"
  9. "github.com/kataras/iris"
  10. "fmt"
  11. )
  12. var (
  13. Users *[]User
  14. )
  15. const (
  16. ERR_USER_NOT_FOUND = "ERR_USER_NOT_FOUND"
  17. ERR_PASSWORD_MISMATCH = "ERR_PASSWORD_MISMATCH"
  18. ERR_SESSION_TIMED_OUT = "ERR_SESSION_TIMED_OUT"
  19. ERR_INVALID_TOKEN = "ERR_INVALID_TOKEN"
  20. )
  21. type User struct {
  22. ID int
  23. Username string
  24. Password string
  25. Mail string
  26. }
  27. func (user *User) Login(username string, password string) (string, error) {
  28. hmacSampleSecret := []byte(configutils.Conf.CryptoKey) // crypto key for JWT encryption
  29. row, err := databaseutils.DBUtil.GetRow("*", "users", "username", username) // get user
  30. if err != nil {
  31. if err.Error() == databaseutils.ERR_EMPTY_RESULT { // empty result -> user not found
  32. return "", errors.New(ERR_USER_NOT_FOUND)
  33. }
  34. fmt.Println("DB ERR @ user Login: ", err)
  35. }
  36. if password == row[2] {
  37. expire, err := time.ParseDuration("168h") // 7 days
  38. if(err != nil) {
  39. return "", errors.New("the hell?")
  40. }
  41. token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
  42. "username": username,
  43. "userid": row[0],
  44. "nbf": time.Now().Unix(),
  45. "exp": time.Now().Add(expire).Unix(),
  46. "token": "nigger", // TODO db based tokens
  47. })
  48. tokenString, _ := token.SignedString(hmacSampleSecret)
  49. user.ID, _ = strconv.Atoi(row[0])
  50. user.Username = row[1]
  51. user.Mail = row[3]
  52. *Users = append(*Users, *user)
  53. fmt.Printf("%v\n", *Users)
  54. return tokenString, nil
  55. } else {
  56. return "", errors.New(ERR_PASSWORD_MISMATCH)
  57. }
  58. }
  59. func searchUser(userID int) int {
  60. for i := range *Users {
  61. if (*Users)[i].ID == userID {
  62. return i
  63. }
  64. }
  65. return -1
  66. }
  67. func VerifyUserLoggedIn(tokenString string) (bool, int, error) { // TODO renew JWT from time to time preventing expiry
  68. hmacSampleSecret := []byte(configutils.Conf.CryptoKey) // crypto key for JWT encryption
  69. token, _ := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
  70. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  71. return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
  72. }
  73. return hmacSampleSecret, nil
  74. })
  75. if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { // if token is valid
  76. if userID, ok := claims["userid"].(string); ok { // extract userID
  77. intUserID, _ := strconv.Atoi(userID) // convert to int ... god i love scripting languages
  78. sliceID := searchUser(intUserID) // verify that user has a session on the server
  79. if sliceID != -1 { // searchUser returns -1 if there's no such user
  80. return true, intUserID, nil
  81. } else {
  82. return false, -1, errors.New(ERR_SESSION_TIMED_OUT) // Session probably expired - may also be faked? TODO more checks?
  83. }
  84. } else {
  85. return false, -1, errors.New("Unknown error") // This should never happen, prolly can't convert something in claims then..
  86. }
  87. } else {
  88. return false, -1, errors.New(ERR_INVALID_TOKEN) // Token is invalid, expired or whatever, TODO switch with ERR_SESSION_TIMED_OUT when database based session system
  89. }
  90. }
  91. func AuthHandler(ctx *iris.Context) {
  92. tokenString := ctx.GetCookie("token")
  93. isAuthed, userID, err := VerifyUserLoggedIn(tokenString)
  94. ctx.Set("userID", userID)
  95. if err != nil {
  96. ctx.Write(err.Error()) // TODO template compatible error handling
  97. }
  98. if isAuthed {
  99. ctx.Next()
  100. } else {
  101. //ctx.Redirect("/login") // TODO redirect after x second when templates are ready
  102. }
  103. }