2019-11-08 06:53:40 +01:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/photoprism/photoprism/internal/config"
|
2019-12-05 19:21:35 +01:00
|
|
|
"github.com/photoprism/photoprism/internal/form"
|
2019-12-28 09:48:36 +01:00
|
|
|
"github.com/photoprism/photoprism/internal/session"
|
2020-01-12 14:00:56 +01:00
|
|
|
"github.com/photoprism/photoprism/pkg/txt"
|
2019-11-08 06:53:40 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// POST /api/v1/session
|
|
|
|
func CreateSession(router *gin.RouterGroup, conf *config.Config) {
|
|
|
|
router.POST("/session", func(c *gin.Context) {
|
2019-12-05 19:21:35 +01:00
|
|
|
var f form.Login
|
2019-11-08 06:53:40 +01:00
|
|
|
|
2019-12-05 19:21:35 +01:00
|
|
|
if err := c.BindJSON(&f); err != nil {
|
2020-01-07 17:36:49 +01:00
|
|
|
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": txt.UcFirst(err.Error())})
|
2019-11-08 06:53:40 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-12-05 19:21:35 +01:00
|
|
|
if f.Password != conf.AdminPassword() {
|
2019-11-08 06:53:40 +01:00
|
|
|
c.AbortWithStatusJSON(400, gin.H{"error": "Invalid password"})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-12-28 09:48:36 +01:00
|
|
|
user := gin.H{"ID": 1, "FirstName": "Admin", "LastName": "", "Role": "admin", "Email": "photoprism@localhost"}
|
2019-11-08 06:53:40 +01:00
|
|
|
|
2019-12-28 09:48:36 +01:00
|
|
|
token := session.Create(user)
|
2019-11-08 06:53:40 +01:00
|
|
|
|
2019-12-28 09:48:36 +01:00
|
|
|
c.Header("X-Session-Token", token)
|
2019-11-08 06:53:40 +01:00
|
|
|
|
2020-01-23 07:39:04 +01:00
|
|
|
s := gin.H{"token": token, "user": user, "config": conf.ClientConfig()}
|
2020-01-22 16:54:01 +01:00
|
|
|
|
2019-11-08 06:53:40 +01:00
|
|
|
c.JSON(http.StatusOK, s)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// DELETE /api/v1/session/
|
|
|
|
func DeleteSession(router *gin.RouterGroup, conf *config.Config) {
|
|
|
|
router.DELETE("/session/:token", func(c *gin.Context) {
|
|
|
|
token := c.Param("token")
|
|
|
|
|
2019-12-28 09:48:36 +01:00
|
|
|
session.Delete(token)
|
2019-11-08 06:53:40 +01:00
|
|
|
|
|
|
|
c.JSON(http.StatusOK, gin.H{"status": "ok", "token": token})
|
|
|
|
})
|
|
|
|
}
|
2019-11-11 21:10:41 +01:00
|
|
|
|
|
|
|
// Returns true, if user doesn't have a valid session token
|
|
|
|
func Unauthorized(c *gin.Context, conf *config.Config) bool {
|
2019-11-12 05:49:10 +01:00
|
|
|
// Always return false if site is public
|
2019-11-11 21:10:41 +01:00
|
|
|
if conf.Public() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2019-11-12 05:49:10 +01:00
|
|
|
// Get session token from HTTP header
|
2019-11-11 21:10:41 +01:00
|
|
|
token := c.GetHeader("X-Session-Token")
|
|
|
|
|
2019-11-12 05:49:10 +01:00
|
|
|
// Check if session token is valid
|
2019-12-28 09:48:36 +01:00
|
|
|
return !session.Exists(token)
|
2019-11-11 21:10:41 +01:00
|
|
|
}
|