2016-05-24 11:55:48 +02:00
|
|
|
package api
|
2016-04-09 21:09:57 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
|
|
|
"encoding/base64"
|
|
|
|
"io"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2016-05-24 11:55:48 +02:00
|
|
|
database "github.com/ansible-semaphore/semaphore/db"
|
2016-04-09 21:09:57 +02:00
|
|
|
"github.com/ansible-semaphore/semaphore/models"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
)
|
|
|
|
|
2017-02-22 23:17:36 +01:00
|
|
|
func getUser(w http.ResponseWriter, r *http.Request) {
|
2016-05-23 21:29:38 +02:00
|
|
|
if u, exists := c.Get("_user"); exists {
|
|
|
|
c.JSON(200, u)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-04-09 21:09:57 +02:00
|
|
|
c.JSON(200, c.MustGet("user"))
|
|
|
|
}
|
|
|
|
|
2017-02-22 23:17:36 +01:00
|
|
|
func getAPITokens(w http.ResponseWriter, r *http.Request) {
|
2016-04-09 21:09:57 +02:00
|
|
|
user := c.MustGet("user").(*models.User)
|
|
|
|
|
|
|
|
var tokens []models.APIToken
|
|
|
|
if _, err := database.Mysql.Select(&tokens, "select * from user__token where user_id=?", user.ID); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
c.JSON(200, tokens)
|
|
|
|
}
|
|
|
|
|
2017-02-22 23:17:36 +01:00
|
|
|
func createAPIToken(w http.ResponseWriter, r *http.Request) {
|
2016-04-09 21:09:57 +02:00
|
|
|
user := c.MustGet("user").(*models.User)
|
|
|
|
tokenID := make([]byte, 32)
|
|
|
|
if _, err := io.ReadFull(rand.Reader, tokenID); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
token := models.APIToken{
|
|
|
|
ID: strings.ToLower(base64.URLEncoding.EncodeToString(tokenID)),
|
|
|
|
Created: time.Now(),
|
|
|
|
UserID: user.ID,
|
|
|
|
Expired: false,
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := database.Mysql.Insert(&token); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
c.JSON(201, token)
|
|
|
|
}
|
|
|
|
|
2017-02-22 23:17:36 +01:00
|
|
|
func expireAPIToken(w http.ResponseWriter, r *http.Request) {
|
2016-04-09 21:09:57 +02:00
|
|
|
user := c.MustGet("user").(*models.User)
|
|
|
|
|
|
|
|
tokenID := c.Param("token_id")
|
|
|
|
res, err := database.Mysql.Exec("update user__token set expired=1 where id=? and user_id=?", tokenID, user.ID)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
affected, err := res.RowsAffected()
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
2016-04-30 14:28:47 +02:00
|
|
|
if affected == 0 {
|
2017-02-22 23:17:36 +01:00
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
2016-04-30 14:28:47 +02:00
|
|
|
return
|
2016-04-09 21:09:57 +02:00
|
|
|
}
|
|
|
|
|
2017-02-22 23:17:36 +01:00
|
|
|
w.WriteHeader(http.StatusNoContent)
|
2016-04-09 21:09:57 +02:00
|
|
|
}
|