| 14 | |
| 15 | |
| 16 | class FoundationDB(MyDB): |
| 17 | |
| 18 | # implemented |
| 19 | def create_authorization_code(self, username, authorization_code, scope) -> bool: |
| 20 | def create_authorization_code_work(tx) -> bool: |
| 21 | cypher = """ |
| 22 | MATCH (u:User) |
| 23 | WHERE u.username = $username |
| 24 | OPTIONAL MATCH (u)-[r1:CAN_USE]->(t:Token) |
| 25 | WITH u, t |
| 26 | DETACH DELETE t |
| 27 | MERGE (u)-[r:CAN_USE]->(ac:AuthorizationCode) |
| 28 | SET ac.code = $authorization_code |
| 29 | SET ac.scope = $scope |
| 30 | WITH ac |
| 31 | CALL apoc.ttl.expireIn(ac, $time_delta, 's') |
| 32 | RETURN ac AS authorization_code |
| 33 | """ |
| 34 | result = tx.run( |
| 35 | cypher, |
| 36 | username=username, |
| 37 | authorization_code=authorization_code, |
| 38 | scope=scope, |
| 39 | time_delta=int(os.environ["SECURITY_AUTHORIZATION_CODE_EXPIRE_SECONDS"]), |
| 40 | ) |
| 41 | summary = result.consume() |
| 42 | if summary.counters.nodes_created < 1: |
| 43 | raise HTTPException(status_code=400, detail="Authorization code was not created.") |
| 44 | return summary.counters.nodes_created |
| 45 | |
| 46 | with self.driver.session() as session: |
| 47 | return session.execute_write(create_authorization_code_work) |
| 48 | |
| 49 | def use_authorization_code(self, authorization_code) -> TokenInfo: |
| 50 | def use_code_to_get_user_info_work(tx) -> TokenData: |
| 51 | cypher = """ |
| 52 | MATCH (u:User)-[r1:CAN_USE]->(ac:AuthorizationCode) |
| 53 | WHERE ac.code = $authorization_code |
| 54 | WITH u.username AS username, ac.scope AS scope |
| 55 | RETURN |
| 56 | username, scope |
| 57 | """ |
| 58 | result = tx.run(cypher, authorization_code=authorization_code) |
| 59 | first = result.single() |
| 60 | if first is None: |
| 61 | raise HTTPException(status_code=404, detail="Authorization code not found.") |
| 62 | authorized_user = TokenData() |
| 63 | authorized_user.username = first.get("username") |
| 64 | authorized_user.scopes = first.get("scope").split(" ") |
| 65 | return authorized_user |
| 66 | |
| 67 | with self.driver.session() as session: |
| 68 | user_info = session.execute_read(use_code_to_get_user_info_work) |
| 69 | |
| 70 | token_info = TokenInfo() |
| 71 | token_info.access_token = create_access_token( |
| 72 | user_info.dict(), timedelta(seconds=int(os.environ["SECURITY_ACCESS_TOKEN_EXPIRE_SECONDS"])) |
| 73 | ) |