GraphQL API and utilities for the rpdata project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

331 lines
8.9 KiB

  1. package services
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "encoding/base64"
  6. "errors"
  7. "fmt"
  8. "git.aiterp.net/rpdata/api/models"
  9. "git.aiterp.net/rpdata/api/repositories"
  10. "github.com/dgrijalva/jwt-go"
  11. "log"
  12. "net/http"
  13. "reflect"
  14. "strings"
  15. "time"
  16. )
  17. var contextKey = &struct{ data string }{"Token Context Key"}
  18. // ErrNoKid is returned if the key id is missing from the jwt token header,
  19. var ErrNoKid = errors.New("missing \"kid\" field in token")
  20. // ErrKeyNotFound is returned if the key wasn't found.
  21. var ErrKeyNotFound = errors.New("key not found")
  22. // ErrInvalidClaims is returned by parseClaims if the claims cannot be parsed
  23. var ErrInvalidClaims = errors.New("invalid claims in token")
  24. // ErrExpired is returned by parseClaims if the expiry date is in the past
  25. var ErrExpired = errors.New("claims have already expired")
  26. // ErrWrongUser is returned by CheckToken if the key cannot represent this user
  27. var ErrWrongUser = errors.New("key is not valid for this user")
  28. // ErrDeletedUser is returned by CheckToken if the key can represent this user, but the user doesn't exist.
  29. var ErrDeletedUser = errors.New("user was not found")
  30. // ErrUnauthenticated is returned when the user is not authenticated
  31. var ErrUnauthenticated = errors.New("you are not authenticated")
  32. // ErrUnauthorized is returned when the user doesn't have access to this resource
  33. var ErrUnauthorized = errors.New("you are not authorized to perform this action")
  34. // ErrInvalidOperation is returned for operations that should never be allowed
  35. var ErrInvalidOperation = errors.New("no permission exists for this operation")
  36. // AuthService is a service for handling the 'orizations and 'entications.
  37. type AuthService struct {
  38. keys repositories.KeyRepository
  39. users repositories.UserRepository
  40. }
  41. // FindKey finds a key by id.
  42. func (s *AuthService) FindKey(ctx context.Context, id string) (*models.Key, error) {
  43. return s.keys.Find(ctx, id)
  44. }
  45. // FindKey finds a key by id.
  46. func (s *AuthService) FindUser(ctx context.Context, id string) (*models.User, error) {
  47. return s.users.Find(ctx, id)
  48. }
  49. // CreateKey generates a new key for the user and name. This
  50. // does not allow generating wildcard keys, they have to be
  51. // manually inserted into the DB.
  52. func (s *AuthService) CreateKey(ctx context.Context, name, user string) (*models.Key, error) {
  53. if user == "*" {
  54. return nil, errors.New("auth: wildcard keys not allowed")
  55. }
  56. secret, err := s.generateSecret()
  57. if err != nil {
  58. return nil, err
  59. }
  60. key := &models.Key{
  61. Name: name,
  62. User: user,
  63. Secret: secret,
  64. }
  65. key, err = s.keys.Insert(ctx, *key)
  66. if err != nil {
  67. return nil, err
  68. }
  69. return key, nil
  70. }
  71. // CheckPermission does some magic.
  72. func (s *AuthService) CheckPermission(ctx context.Context, op string, obj interface{}) error {
  73. token := s.TokenFromContext(ctx)
  74. if token == nil {
  75. return ErrUnauthenticated
  76. }
  77. if v := reflect.ValueOf(obj); v.Kind() == reflect.Struct {
  78. ptr := reflect.PtrTo(v.Type())
  79. ptrValue := reflect.New(ptr.Elem())
  80. ptrValue.Elem().Set(v)
  81. obj = ptrValue.Interface()
  82. }
  83. var authorized = false
  84. switch v := obj.(type) {
  85. case *models.Channel:
  86. authorized = token.Permitted("channel." + op)
  87. case *models.Character:
  88. authorized = token.PermittedUser(v.Author, "member", "character."+op)
  89. case *models.Chapter:
  90. authorized = token.PermittedUser(v.Author, "member", "chapter."+op)
  91. case *models.Comment:
  92. if op == "add" && v.Author != token.UserID {
  93. return ErrInvalidOperation
  94. }
  95. authorized = token.PermittedUser(v.Author, "member", "comment."+op)
  96. case *models.File:
  97. authorized = token.PermittedUser(v.Author, "member", "file."+op)
  98. case *models.Log:
  99. authorized = token.Permitted("log." + op)
  100. case *models.Post:
  101. authorized = token.Permitted("post." + op)
  102. case *models.Story:
  103. authorized = token.PermittedUser(v.Author, "member", "story."+op)
  104. case *models.User:
  105. authorized = token.Permitted("user." + op)
  106. default:
  107. log.Panicf("Invalid model %T: %#+v", v, v)
  108. }
  109. if !authorized {
  110. return ErrUnauthorized
  111. }
  112. return nil
  113. }
  114. // TokenFromContext gets the token from context.
  115. func (s *AuthService) TokenFromContext(ctx context.Context) *models.Token {
  116. token, ok := ctx.Value(contextKey).(*models.Token)
  117. if !ok {
  118. return nil
  119. }
  120. return token
  121. }
  122. // RequestWithToken either returns the request, or the request with a new context that
  123. // has the token.
  124. func (s *AuthService) RequestWithToken(r *http.Request) *http.Request {
  125. header := r.Header.Get("Authorization")
  126. if header == "" {
  127. return r
  128. }
  129. if !strings.HasPrefix(header, "Bearer ") {
  130. return r
  131. }
  132. token, err := s.CheckToken(r.Context(), header[7:])
  133. if err != nil {
  134. return r
  135. }
  136. return r.WithContext(context.WithValue(r.Context(), contextKey, &token))
  137. }
  138. // CheckToken reads the token string and returns a token if everything is kosher.
  139. func (s *AuthService) CheckToken(ctx context.Context, tokenString string) (token models.Token, err error) {
  140. var key *models.Key
  141. jwtToken, err := jwt.Parse(tokenString, func(jwtToken *jwt.Token) (interface{}, error) {
  142. if _, ok := jwtToken.Method.(*jwt.SigningMethodHMAC); !ok {
  143. return nil, fmt.Errorf("unexpected signing method: %v", jwtToken.Header["alg"])
  144. }
  145. kid, ok := jwtToken.Header["kid"].(string)
  146. if !ok {
  147. return nil, ErrNoKid
  148. }
  149. key, err = s.FindKey(ctx, kid)
  150. if err != nil || key.ID == "" {
  151. return nil, ErrKeyNotFound
  152. }
  153. return []byte(key.Secret), nil
  154. })
  155. if err != nil {
  156. return models.Token{}, err
  157. }
  158. userid, permissions, err := s.parseClaims(jwtToken.Claims)
  159. if err != nil {
  160. return models.Token{}, err
  161. }
  162. if !key.ValidForUser(userid) {
  163. return models.Token{}, ErrWrongUser
  164. }
  165. user, err := s.ensureUser(ctx, userid)
  166. if err != nil {
  167. return models.Token{}, ErrDeletedUser
  168. }
  169. acceptedPermissions := make([]string, 0, len(user.Permissions))
  170. if len(permissions) > 0 {
  171. for _, permission := range permissions {
  172. found := false
  173. for _, userPermission := range user.Permissions {
  174. if permission == userPermission {
  175. found = true
  176. break
  177. }
  178. }
  179. if found {
  180. acceptedPermissions = append(acceptedPermissions, permission)
  181. }
  182. }
  183. } else {
  184. acceptedPermissions = append(acceptedPermissions, user.Permissions...)
  185. }
  186. return models.Token{UserID: user.ID, Permissions: acceptedPermissions}, nil
  187. }
  188. // AllPermissions gets all permissions and their purpose
  189. func (s *AuthService) AllPermissions() map[string]string {
  190. return map[string]string{
  191. "member": "Can add/edit/remove own content",
  192. "user.edit": "Can edit non-owned users",
  193. "character.add": "Can add non-owned characters",
  194. "character.edit": "Can edit non-owned characters",
  195. "character.remove": "Can remove non-owned characters",
  196. "channel.add": "Can add channels",
  197. "channel.edit": "Can edit channels",
  198. "channel.remove": "Can remove channels",
  199. "comment.edit": "Can edit non-owned comments",
  200. "comment.remove": "Can remove non-owned comments",
  201. "log.add": "Can add logs",
  202. "log.edit": "Can edit logs",
  203. "log.remove": "Can remove logs",
  204. "post.add": "Can add posts",
  205. "post.edit": "Can edit posts",
  206. "post.move": "Can move posts",
  207. "post.remove": "Can remove posts",
  208. "story.add": "Can add non-owned stories",
  209. "story.edit": "Can edit non-owned stories",
  210. "story.remove": "Can remove non-owned stories",
  211. "story.unlisted": "Can view non-owned unlisted stories",
  212. "file.upload": "Can upload files",
  213. "file.list": "Can list non-owned files",
  214. "file.view": "Can view non-owned files",
  215. "file.edit": "Can edit non-owned files",
  216. "file.remove": "Can remove non-owned files",
  217. }
  218. }
  219. func (s *AuthService) parseClaims(jwtClaims jwt.Claims) (userid string, permissions []string, err error) {
  220. mapClaims, ok := jwtClaims.(jwt.MapClaims)
  221. if !ok {
  222. return "", nil, ErrInvalidClaims
  223. }
  224. if !mapClaims.VerifyExpiresAt(time.Now().Unix(), true) {
  225. return "", nil, ErrExpired
  226. }
  227. if userid, ok = mapClaims["user"].(string); !ok {
  228. return "", nil, ErrInvalidClaims
  229. }
  230. if claimedPermissions, ok := mapClaims["permissions"].([]interface{}); ok {
  231. for _, permission := range claimedPermissions {
  232. if permission, ok := permission.(string); ok {
  233. permissions = append(permissions, permission)
  234. }
  235. }
  236. if len(permissions) == 0 {
  237. return "", nil, ErrInvalidClaims
  238. }
  239. }
  240. return
  241. }
  242. func (s *AuthService) generateSecret() (string, error) {
  243. var data [64]byte
  244. _, err := rand.Read(data[:])
  245. if err != nil {
  246. return "", err
  247. }
  248. return base64.RawURLEncoding.EncodeToString(data[:]), nil
  249. }
  250. func (s *AuthService) ensureUser(ctx context.Context, id string) (*models.User, error) {
  251. user, err := s.users.Find(ctx, id)
  252. if err == repositories.ErrNotFound {
  253. user = &models.User{
  254. ID: id,
  255. Nick: "",
  256. Permissions: []string{
  257. "member",
  258. "log.edit",
  259. "post.edit",
  260. "post.move",
  261. "post.remove",
  262. "file.upload",
  263. },
  264. }
  265. user, err = s.users.Insert(ctx, *user)
  266. if err != nil {
  267. return nil, err
  268. }
  269. } else if err != nil {
  270. return nil, err
  271. }
  272. return user, err
  273. }