2019-03-08 08:15:38 -06:00
package api
import (
2019-04-30 07:42:01 -05:00
"context"
2020-11-19 06:34:28 -06:00
"errors"
2021-11-29 03:18:01 -06:00
"net/http"
2019-03-08 08:15:38 -06:00
"time"
2023-01-30 02:18:26 -06:00
"github.com/ua-parser/uap-go/uaparser"
2019-03-08 08:15:38 -06:00
"github.com/grafana/grafana/pkg/api/dtos"
2021-01-15 07:43:20 -06:00
"github.com/grafana/grafana/pkg/api/response"
2023-03-23 08:39:04 -05:00
"github.com/grafana/grafana/pkg/infra/network"
2022-11-18 02:56:06 -06:00
"github.com/grafana/grafana/pkg/services/auth"
2023-03-23 08:39:04 -05:00
"github.com/grafana/grafana/pkg/services/authn"
2023-01-27 01:50:36 -06:00
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
2022-07-20 07:50:06 -05:00
"github.com/grafana/grafana/pkg/services/user"
2019-03-08 08:15:38 -06:00
"github.com/grafana/grafana/pkg/util"
2021-11-29 03:18:01 -06:00
"github.com/grafana/grafana/pkg/web"
2019-03-08 08:15:38 -06:00
)
2022-07-27 08:54:37 -05:00
// swagger:route GET /user/auth-tokens signed_in_user getUserAuthTokens
//
// Auth tokens of the actual User.
//
// Return a list of all auth tokens (devices) that the actual user currently have logged in from.
//
// Responses:
// 200: getUserAuthTokensResponse
// 401: unauthorisedError
// 403: forbiddenError
// 500: internalServerError
2023-01-27 01:50:36 -06:00
func ( hs * HTTPServer ) GetUserAuthTokens ( c * contextmodel . ReqContext ) response . Response {
2022-08-11 06:28:55 -05:00
return hs . getUserAuthTokensInternal ( c , c . UserID )
2019-03-08 08:15:38 -06:00
}
2022-07-27 08:54:37 -05:00
// swagger:route POST /user/revoke-auth-token signed_in_user revokeUserAuthToken
//
// Revoke an auth token of the actual User.
//
// Revokes the given auth token (device) for the actual user. User of issued auth token (device) will no longer be logged in and will be required to authenticate again upon next activity.
//
// Responses:
// 200: okResponse
// 400: badRequestError
// 401: unauthorisedError
// 403: forbiddenError
// 500: internalServerError
2023-01-27 01:50:36 -06:00
func ( hs * HTTPServer ) RevokeUserAuthToken ( c * contextmodel . ReqContext ) response . Response {
2022-11-18 02:56:06 -06:00
cmd := auth . RevokeAuthTokenCmd { }
2021-11-29 03:18:01 -06:00
if err := web . Bind ( c . Req , & cmd ) ; err != nil {
return response . Error ( http . StatusBadRequest , "bad request data" , err )
}
2022-08-11 06:28:55 -05:00
return hs . revokeUserAuthTokenInternal ( c , c . UserID , cmd )
2019-03-08 08:15:38 -06:00
}
2023-03-23 08:39:04 -05:00
func ( hs * HTTPServer ) RotateUserAuthTokenRedirect ( c * contextmodel . ReqContext ) response . Response {
if err := hs . rotateToken ( c ) ; err != nil {
hs . log . FromContext ( c . Req . Context ( ) ) . Debug ( "Failed to rotate token" , "error" , err )
if errors . Is ( err , auth . ErrInvalidSessionToken ) {
authn . DeleteSessionCookie ( c . Resp , hs . Cfg )
}
return response . Redirect ( hs . Cfg . AppSubURL + "/login" )
}
return response . Redirect ( hs . GetRedirectURL ( c ) )
}
// swagger:route POST /user/auth-tokens/rotate
//
// # Rotate the auth token of the caller
//
// Rotate the token of caller, if successful send a new session cookie.
//
// Responses:
// 200: okResponse
// 401: unauthorisedError
// 404: notFoundError
// 500: internalServerError
func ( hs * HTTPServer ) RotateUserAuthToken ( c * contextmodel . ReqContext ) response . Response {
if err := hs . rotateToken ( c ) ; err != nil {
hs . log . FromContext ( c . Req . Context ( ) ) . Debug ( "Failed to rotate token" , "error" , err )
if errors . Is ( err , auth . ErrInvalidSessionToken ) {
authn . DeleteSessionCookie ( c . Resp , hs . Cfg )
return response . ErrOrFallback ( http . StatusUnauthorized , http . StatusText ( http . StatusUnauthorized ) , err )
}
if errors . Is ( err , auth . ErrUserTokenNotFound ) {
2023-03-31 09:44:08 -05:00
return response . ErrOrFallback ( http . StatusUnauthorized , http . StatusText ( http . StatusUnauthorized ) , err )
2023-03-23 08:39:04 -05:00
}
return response . ErrOrFallback ( http . StatusInternalServerError , http . StatusText ( http . StatusInternalServerError ) , err )
}
return response . JSON ( http . StatusOK , map [ string ] any { } )
}
func ( hs * HTTPServer ) rotateToken ( c * contextmodel . ReqContext ) error {
token := c . GetCookie ( hs . Cfg . LoginCookieName )
ip , err := network . GetIPFromAddress ( c . RemoteAddr ( ) )
if err != nil {
hs . log . Debug ( "Failed to get IP from client address" , "addr" , c . RemoteAddr ( ) )
}
res , err := hs . AuthTokenService . RotateToken ( c . Req . Context ( ) , auth . RotateCommand {
UnHashedToken : token ,
IP : ip ,
UserAgent : c . Req . UserAgent ( ) ,
} )
if err != nil {
return err
}
if res . UnhashedToken != token {
authn . WriteSessionCookie ( c . Resp , hs . Cfg , res )
}
return nil
}
2021-01-15 07:43:20 -06:00
func ( hs * HTTPServer ) logoutUserFromAllDevicesInternal ( ctx context . Context , userID int64 ) response . Response {
2022-08-02 09:58:05 -05:00
userQuery := user . GetUserByIDQuery { ID : userID }
2019-03-08 08:15:38 -06:00
2022-08-02 09:58:05 -05:00
_ , err := hs . userService . GetByID ( ctx , & userQuery )
if err != nil {
2022-07-20 07:50:06 -05:00
if errors . Is ( err , user . ErrUserNotFound ) {
2021-01-15 07:43:20 -06:00
return response . Error ( 404 , "User not found" , err )
2019-03-08 08:15:38 -06:00
}
2021-01-15 07:43:20 -06:00
return response . Error ( 500 , "Could not read user from database" , err )
2019-03-08 08:15:38 -06:00
}
2022-08-02 09:58:05 -05:00
err = hs . AuthTokenService . RevokeAllUserTokens ( ctx , userID )
2019-03-08 08:15:38 -06:00
if err != nil {
2021-01-15 07:43:20 -06:00
return response . Error ( 500 , "Failed to logout user" , err )
2019-03-08 08:15:38 -06:00
}
2022-04-15 07:01:58 -05:00
return response . JSON ( http . StatusOK , util . DynMap {
2019-03-08 08:15:38 -06:00
"message" : "User logged out" ,
} )
}
2023-01-27 01:50:36 -06:00
func ( hs * HTTPServer ) getUserAuthTokensInternal ( c * contextmodel . ReqContext , userID int64 ) response . Response {
2022-08-02 09:58:05 -05:00
userQuery := user . GetUserByIDQuery { ID : userID }
2019-03-08 08:15:38 -06:00
2022-08-02 09:58:05 -05:00
_ , err := hs . userService . GetByID ( c . Req . Context ( ) , & userQuery )
if err != nil {
2022-07-20 07:50:06 -05:00
if errors . Is ( err , user . ErrUserNotFound ) {
2022-06-24 09:59:45 -05:00
return response . Error ( http . StatusNotFound , "User not found" , err )
2022-07-20 07:50:06 -05:00
} else if errors . Is ( err , user . ErrCaseInsensitive ) {
2022-06-24 09:59:45 -05:00
return response . Error ( http . StatusConflict ,
"User has conflicting login or email with another user. Please contact server admin" , err )
2019-03-08 08:15:38 -06:00
}
2022-06-24 09:59:45 -05:00
return response . Error ( http . StatusInternalServerError , "Failed to get user" , err )
2019-03-08 08:15:38 -06:00
}
2020-11-05 08:37:11 -06:00
tokens , err := hs . AuthTokenService . GetUserTokens ( c . Req . Context ( ) , userID )
2019-03-08 08:15:38 -06:00
if err != nil {
2021-01-15 07:43:20 -06:00
return response . Error ( 500 , "Failed to get user auth tokens" , err )
2019-03-08 08:15:38 -06:00
}
result := [ ] * dtos . UserToken { }
for _ , token := range tokens {
isActive := false
if c . UserToken != nil && c . UserToken . Id == token . Id {
isActive = true
}
2019-06-11 07:12:52 -05:00
parser := uaparser . NewFromSaved ( )
client := parser . Parse ( token . UserAgent )
osVersion := ""
if client . Os . Major != "" {
osVersion = client . Os . Major
if client . Os . Minor != "" {
osVersion = osVersion + "." + client . Os . Minor
}
}
browserVersion := ""
if client . UserAgent . Major != "" {
browserVersion = client . UserAgent . Major
if client . UserAgent . Minor != "" {
browserVersion = browserVersion + "." + client . UserAgent . Minor
}
}
2019-07-08 07:30:02 -05:00
createdAt := time . Unix ( token . CreatedAt , 0 )
seenAt := time . Unix ( token . SeenAt , 0 )
if token . SeenAt == 0 {
seenAt = createdAt
}
2019-03-08 08:15:38 -06:00
result = append ( result , & dtos . UserToken {
2019-06-11 07:12:52 -05:00
Id : token . Id ,
IsActive : isActive ,
ClientIp : token . ClientIp ,
Device : client . Device . ToString ( ) ,
OperatingSystem : client . Os . Family ,
OperatingSystemVersion : osVersion ,
Browser : client . UserAgent . Family ,
BrowserVersion : browserVersion ,
2019-07-08 07:30:02 -05:00
CreatedAt : createdAt ,
SeenAt : seenAt ,
2019-03-08 08:15:38 -06:00
} )
}
2022-04-15 07:01:58 -05:00
return response . JSON ( http . StatusOK , result )
2019-03-08 08:15:38 -06:00
}
2023-01-27 01:50:36 -06:00
func ( hs * HTTPServer ) revokeUserAuthTokenInternal ( c * contextmodel . ReqContext , userID int64 , cmd auth . RevokeAuthTokenCmd ) response . Response {
2022-08-02 09:58:05 -05:00
userQuery := user . GetUserByIDQuery { ID : userID }
_ , err := hs . userService . GetByID ( c . Req . Context ( ) , & userQuery )
if err != nil {
2022-07-20 07:50:06 -05:00
if errors . Is ( err , user . ErrUserNotFound ) {
2021-01-15 07:43:20 -06:00
return response . Error ( 404 , "User not found" , err )
2019-03-08 08:15:38 -06:00
}
2021-01-15 07:43:20 -06:00
return response . Error ( 500 , "Failed to get user" , err )
2019-03-08 08:15:38 -06:00
}
2020-11-05 08:37:11 -06:00
token , err := hs . AuthTokenService . GetUserToken ( c . Req . Context ( ) , userID , cmd . AuthTokenId )
2019-03-08 08:15:38 -06:00
if err != nil {
2022-11-18 02:56:06 -06:00
if errors . Is ( err , auth . ErrUserTokenNotFound ) {
2021-01-15 07:43:20 -06:00
return response . Error ( 404 , "User auth token not found" , err )
2019-03-08 08:15:38 -06:00
}
2021-01-15 07:43:20 -06:00
return response . Error ( 500 , "Failed to get user auth token" , err )
2019-03-08 08:15:38 -06:00
}
if c . UserToken != nil && c . UserToken . Id == token . Id {
2021-01-15 07:43:20 -06:00
return response . Error ( 400 , "Cannot revoke active user auth token" , nil )
2019-03-08 08:15:38 -06:00
}
2023-03-31 09:44:08 -05:00
err = hs . AuthTokenService . RevokeToken ( c . Req . Context ( ) , token , false )
2019-03-08 08:15:38 -06:00
if err != nil {
2022-11-18 02:56:06 -06:00
if errors . Is ( err , auth . ErrUserTokenNotFound ) {
2021-01-15 07:43:20 -06:00
return response . Error ( 404 , "User auth token not found" , err )
2019-03-08 08:15:38 -06:00
}
2021-01-15 07:43:20 -06:00
return response . Error ( 500 , "Failed to revoke user auth token" , err )
2019-03-08 08:15:38 -06:00
}
2022-04-15 07:01:58 -05:00
return response . JSON ( http . StatusOK , util . DynMap {
2019-03-08 08:15:38 -06:00
"message" : "User auth token revoked" ,
} )
}
2022-07-27 08:54:37 -05:00
// swagger:parameters revokeUserAuthToken
type RevokeUserAuthTokenParams struct {
// in:body
// required:true
2022-11-18 02:56:06 -06:00
Body auth . RevokeAuthTokenCmd ` json:"body" `
2022-07-27 08:54:37 -05:00
}
// swagger:response getUserAuthTokensResponse
type GetUserAuthTokensResponse struct {
// in:body
2022-11-18 02:56:06 -06:00
Body [ ] * auth . UserToken ` json:"body" `
2022-07-27 08:54:37 -05:00
}