Semaphore/routes/auth.go

86 lines
2.0 KiB
Go
Raw Normal View History

2016-01-05 00:32:53 +01:00
package routes
import (
"database/sql"
2016-01-05 00:32:53 +01:00
"fmt"
"strings"
2016-01-05 00:32:53 +01:00
"time"
2016-03-16 22:49:43 +01:00
"github.com/ansible-semaphore/semaphore/database"
"github.com/ansible-semaphore/semaphore/models"
"github.com/ansible-semaphore/semaphore/util"
"github.com/gin-gonic/gin"
2016-01-05 00:32:53 +01:00
)
func authentication(c *gin.Context) {
var userID int
if authHeader := strings.ToLower(c.Request.Header.Get("authorization")); len(authHeader) > 0 {
var token models.APIToken
if err := database.Mysql.SelectOne(&token, "select * from user__token where id=? and expired=0", strings.Replace(authHeader, "bearer ", "", 1)); err != nil {
if err == sql.ErrNoRows {
c.AbortWithStatus(403)
return
}
panic(err)
2016-01-05 00:32:53 +01:00
}
userID = token.UserID
} else {
// fetch session from cookie
cookie, err := c.Request.Cookie("semaphore")
if err != nil {
c.AbortWithStatus(403)
return
}
2016-01-05 00:32:53 +01:00
value := make(map[string]interface{})
if err = util.Cookie.Decode("semaphore", cookie.Value, &value); err != nil {
c.AbortWithStatus(403)
2016-01-05 00:32:53 +01:00
panic(err)
}
user, ok := value["user"]
sessionVal, okSession := value["session"]
if !ok || !okSession {
c.AbortWithStatus(403)
return
}
2016-01-05 00:32:53 +01:00
userID = user.(int)
sessionID := sessionVal.(int)
2016-01-05 00:32:53 +01:00
// fetch session
var session models.Session
if err := database.Mysql.SelectOne(&session, "select * from session where id=? and user_id=? and expired=0", sessionID, userID); err != nil {
2016-03-18 23:03:28 +01:00
c.AbortWithStatus(403)
return
}
2016-01-05 00:32:53 +01:00
if time.Now().Sub(session.LastActive).Hours() > 7*24 {
// more than week old unused session
// destroy.
if _, err := database.Mysql.Exec("update session set expired=1 where id=?", sessionID); err != nil {
panic(err)
}
2016-01-05 00:32:53 +01:00
c.AbortWithStatus(403)
return
}
if _, err := database.Mysql.Exec("update session set last_active=NOW() where id=?", sessionID); err != nil {
panic(err)
}
}
2016-01-05 00:32:53 +01:00
user, err := models.FetchUser(userID)
if err != nil {
fmt.Println("Can't find user", err)
c.AbortWithStatus(403)
2016-01-05 00:32:53 +01:00
return
}
c.Set("user", user)
2016-01-05 00:32:53 +01:00
}