Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1"""LICENSE 

2Copyright 2020 Hermann Krumrey <hermann@krumreyh.com> 

3 

4This file is part of jerrycan. 

5 

6jerrycan is free software: you can redistribute it and/or modify 

7it under the terms of the GNU General Public License as published by 

8the Free Software Foundation, either version 3 of the License, or 

9(at your option) any later version. 

10 

11jerrycan is distributed in the hope that it will be useful, 

12but WITHOUT ANY WARRANTY; without even the implied warranty of 

13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

14GNU General Public License for more details. 

15 

16You should have received a copy of the GNU General Public License 

17along with jerrycan. If not, see <http://www.gnu.org/licenses/>. 

18LICENSE""" 

19 

20import time 

21from jerrycan.db.User import User 

22from jerrycan.base import db 

23from jerrycan.Config import Config 

24from jerrycan.db.IDModelMixin import IDModelMixin 

25from puffotter.crypto import verify_password 

26 

27 

28class ApiKey(IDModelMixin, db.Model): 

29 """ 

30 Model that describes the 'api_keys' SQL table 

31 An ApiKey is used for API access using HTTP basic auth 

32 """ 

33 

34 __tablename__ = "api_keys" 

35 """ 

36 The name of the table 

37 """ 

38 

39 user_id: int = db.Column( 

40 db.Integer, 

41 db.ForeignKey("users.id"), 

42 nullable=False 

43 ) 

44 """ 

45 The ID of the user associated with this API key 

46 """ 

47 

48 user: User = db.relationship("User", back_populates="api_keys") 

49 """ 

50 The user associated with this API key 

51 """ 

52 

53 key_hash: str = db.Column(db.String(255), nullable=False) 

54 """ 

55 The hash of the API key 

56 """ 

57 

58 creation_time: int = \ 

59 db.Column(db.Integer, nullable=False, default=time.time) 

60 """ 

61 The time at which this API key was created as a UNIX timestamp 

62 """ 

63 

64 def has_expired(self) -> bool: 

65 """ 

66 Checks if the API key has expired. 

67 API Keys expire after 30 days 

68 :return: True if the key has expired, False otherwise 

69 """ 

70 return time.time() - self.creation_time > Config.MAX_API_KEY_AGE 

71 

72 def verify_key(self, key: str) -> bool: 

73 """ 

74 Checks if a given key is valid 

75 :param key: The key to check 

76 :return: True if the key is valid, False otherwise 

77 """ 

78 try: 

79 _id, api_key = key.split(":", 1) 

80 if int(_id) != self.id: 

81 return False 

82 else: 

83 return verify_password(api_key, self.key_hash) 

84 except ValueError: 

85 return False