blob: 45e4637650416d22ff25e0dd12b38f0c2c3ab852 [file] [log] [blame]
Adrià Vilanova Martínezf19ea432024-01-23 20:20:52 +01001# Copyright 2018 The Chromium Authors
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
Copybara854996b2021-09-07 19:36:02 +00004
5"""Context object to hold utility objects used during request processing.
6"""
7from __future__ import print_function
8from __future__ import division
9from __future__ import absolute_import
10
11import logging
12
13from framework import authdata
14from framework import permissions
15from framework import profiler
16from framework import sql
17from framework import template_helpers
18
19
20class MonorailContext(object):
21 """Context with objects used in request handling mechanics.
22
23 Attrributes:
24 cnxn: MonorailConnection to the SQL DB.
25 auth: AuthData object that identifies the account making the request.
26 perms: PermissionSet for requesting user, set by LookupLoggedInUserPerms().
27 profiler: Profiler object.
28 warnings: A list of warnings to present to the user.
29 errors: A list of errors to present to the user.
30
31 Unlike MonorailRequest, this object does not parse any part of the request,
32 retrieve any business objects (other than the User PB for the requesting
33 user), or check any permissions.
34 """
35
36 def __init__(
37 self, services, cnxn=None, requester=None, auth=None, perms=None,
38 autocreate=True):
39 """Construct a MonorailContext.
40
41 Args:
42 services: Connection to backends.
43 cnxn: Optional connection to SQL database.
44 requester: String email address of user making the request or None.
45 auth: AuthData object used during testing.
46 perms: PermissionSet used during testing.
47 autocreate: Set to False to require that a row in the User table already
48 exists for this user, otherwise raise NoSuchUserException.
49 """
50 self.cnxn = cnxn or sql.MonorailConnection()
51 self.auth = auth or authdata.AuthData.FromEmail(
52 self.cnxn, requester, services, autocreate=autocreate)
53 self.perms = perms # Usually None until LookupLoggedInUserPerms() called.
54 self.profiler = profiler.Profiler()
55
56 # TODO(jrobbins): make self.errors not be UI-centric.
57 self.warnings = []
58 self.errors = template_helpers.EZTError()
59
60 def LookupLoggedInUserPerms(self, project):
61 """Look up perms for user making a request in project (can be None)."""
62 with self.profiler.Phase('looking up signed in user permissions'):
63 self.perms = permissions.GetPermissions(
64 self.auth.user_pb, self.auth.effective_ids, project)
65
66 def CleanUp(self):
67 """Close the DB cnxn and any other clean up."""
68 if self.cnxn:
69 self.cnxn.Close()
70 self.cnxn = None
71
72 def __repr__(self):
73 """Return a string more useful for debugging."""
74 return '%s(cnxn=%r, auth=%r, perms=%r)' % (
75 self.__class__.__name__, self.cnxn, self.auth, self.perms)