Moritz Schmidt 9 jaren geleden
bovenliggende
commit
43e4302156
1 gewijzigde bestanden met toevoegingen van 21 en 21 verwijderingen
  1. 21 21
      usermanager.go

+ 21 - 21
usermanager.go

@@ -12,40 +12,37 @@ import (
 )
 
 var (
-  Users *[]User
+  Users *[]User // stores all currently logged in users
 )
 
-const (
+const ( // Error constants
   ERR_USER_NOT_FOUND = "ERR_USER_NOT_FOUND"
   ERR_PASSWORD_MISMATCH = "ERR_PASSWORD_MISMATCH"
   ERR_SESSION_TIMED_OUT = "ERR_SESSION_TIMED_OUT"
   ERR_INVALID_TOKEN = "ERR_INVALID_TOKEN"
 )
 
-type User struct {
+type User struct { // User
   ID int
   Username string
   Password string
   Mail string
 }
 
-
 func (user *User) Login(username string, password string) (string, error) {
   hmacSampleSecret := []byte(configutils.Conf.CryptoKey) // crypto key for JWT encryption
-  row, err := databaseutils.DBUtil.GetRow("*", "users", "username", username) // get user
+  row, err := databaseutils.DBUtil.GetRow("*", "users", "username", username) // get user from db
 
   if err != nil {
     if err.Error() == databaseutils.ERR_EMPTY_RESULT { // empty result -> user not found
       return "", errors.New(ERR_USER_NOT_FOUND)
+    } else {
+      return "", errors.New("Unknown error")
     }
-    fmt.Println("DB ERR @ user Login: ", err)
   }
 
-  if password == row[2] {
-    expire, err := time.ParseDuration("168h") // 7 days
-    if(err != nil) {
-      return "", errors.New("the hell?")
-    }
+  if password == row[2] { // if sent pw == stored pw // TODO md5/crypto
+    expire, _ := time.ParseDuration("168h") // 7 days
 
     token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
       "username": username,
@@ -61,14 +58,13 @@ func (user *User) Login(username string, password string) (string, error) {
     user.Username = row[1]
     user.Mail = row[3]
 
-    *Users = append(*Users, *user)
+    *Users = append(*Users, *user) // store user in logged-in-users list
 
-    fmt.Printf("%v\n", *Users)
+    //fmt.Printf("%v\n", *Users) // DEBUG
 
-    return tokenString, nil
+    return tokenString, nil // return tokenString (Cookie)
   } else {
-
-    return "", errors.New(ERR_PASSWORD_MISMATCH)
+    return "", errors.New(ERR_PASSWORD_MISMATCH) // wrong password
   }
 }
 
@@ -82,6 +78,10 @@ func searchUser(userID int) int {
 }
 
 func VerifyUserLoggedIn(tokenString string) (bool, int, error) { // TODO renew JWT from time to time preventing expiry
+  if tokenString == "" { // if no tokenString("Cookie") exists fail
+    return false, -1, errors.New(ERR_INVALID_TOKEN)
+  }
+
   hmacSampleSecret := []byte(configutils.Conf.CryptoKey) // crypto key for JWT encryption
 
   token, _ := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
@@ -96,7 +96,7 @@ func VerifyUserLoggedIn(tokenString string) (bool, int, error) { // TODO renew J
       intUserID, _ := strconv.Atoi(userID) // convert to int ... god i love scripting languages
       sliceID := searchUser(intUserID) // verify that user has a session on the server
       if sliceID != -1 { // searchUser returns -1 if there's no such user
-        return true, intUserID, nil
+        return true, intUserID, nil // logged in
       } else {
         return false, -1, errors.New(ERR_SESSION_TIMED_OUT) // Session probably expired - may also be faked? TODO more checks?
       }
@@ -112,15 +112,15 @@ func AuthHandler(ctx *iris.Context) {
   tokenString := ctx.GetCookie("token")
   isAuthed, userID, err := VerifyUserLoggedIn(tokenString)
 
-  ctx.Set("userID", userID)
+  ctx.Set("userID", userID) // save userID for in-context use
 
   if err != nil {
-    ctx.Write(err.Error()) // TODO template compatible error handling
+    fmt.Println("Auth error: ", err.Error())
   }
 
   if isAuthed {
-    ctx.Next()
+    ctx.Next() // successfully authed, next handler
   } else {
-    //ctx.Redirect("/login") // TODO redirect after x second when templates are ready
+    ctx.Render("login.html", struct{ Error string }{Error: err.Error()}) // failed to auth
   }
 }