def doGetByEmail(self, email): current_user = self.getCurrentUser() assurances = Assurance.getByUser(current_user) if 'assurer' in assurances: user = User.getByEmail(email) if user is None: raise ReportedError([noSuchUser], status=404) return self.as_dict(user) raise ReportedError([noAuthorization], status=403)
def checkIdAgainstFacebookMe(self, form): code = form.password.data try: resp = self.facebookMe(code) except urllib.error.HTTPError as err: raise ReportedError([cannotLoginToFacebook, err.read()], 403) data = json.loads(resp) if data["id"] != form.identifier.data: raise ReportedError(["bad facebook id"], 403)
def validateUrlQueryParams(self, params): if 'redirect_uri' not in params: raise ReportedError(missingParameterUrlQuery, 400) if 'response_type' not in params: raise ReportedError(missingParameterResponse, 302, params['redirect_uri']) if 'client_id' not in params: raise ReportedError(missingParameterClientId, 302, params['redirect_uri'])
def doRemoveCredential(self, form): session = self.getSession() if self.isLoginCredential(form, session): raise ReportedError([cannotDeleteLoginCred],400) cred=Credential.get(form.credentialType.data, form.identifier.data) if cred is None: raise ReportedError([noSuchCredential], 404) cred.rm() return self.simple_response(credentialRemoved)
def validate_redirect_uri(self, client_id, redirect_uri, message=invalidRequest, errorCode=302): app = Application.get(client_id) if self.isEmpty(app): raise ReportedError(message, errorCode, uri=redirect_uri) if not app.redirect_uri == redirect_uri.split("?")[0]: raise ReportedError(message, errorCode, uri=redirect_uri)
def get_token(self, form): self.validateGetTokenParameters(form) if not form.code.data: raise ReportedError(invalidGrant, 400) data = self.from_authorization_code(form.client_id.data, form.code.data, form.scope.data) if self.isEmpty(data): raise ReportedError(invalidGrant, 400) self.discard_authorization_code(form.client_id.data, form.code.data) return self.persistAndRespond(form.client_id.data, data.user_id)
def doDeregistrationDoit(self, form): Credential.deleteExpired('deregister') secret = form.deregister_secret.data if secret is None: raise ReportedError( [secretIsNeededForDeregistrationDoit],400) deregistrationCredential = Credential.getBySecret('deregister', secret) if deregistrationCredential is None: raise ReportedError([badDeregistrationSecret],400) user = deregistrationCredential.user self.removeUser(user) return self.simple_response(youAreDeregistered)
def getDataOfUserForAuthenticator(self, userid, authuser, authenticator): user = User.get(userid) if not user: raise ReportedError([noSuchUser], status=404) if self.doesUserAskOwnData(userid, authenticator): return self.shownDataForUser(user) if self.doesUserAskForOthersData(authuser, authenticator): assurances = Assurance.getByUser(authuser) if 'assurer' in assurances: return self.shownDataForAssurer(user) else: raise ReportedError([noShowAuthorization], status=403) return self.shownDataForApp(user, authenticator)
def sendEmail(self, user, secret, expiry, topic, rmuser=False, recipient=None, **addfields): if recipient is None: recipient = user.email emailData = EmailData(user.email, secret, expiry, addfields) bodyTextCfg = topic + '_EMAIL_BODY_TEXT' bodyHtmlCfg = topic + '_EMAIL_BODY_HTML' subjectCfg = topic + '_EMAIL_SUBJECT' text = self.getConfig(bodyTextCfg).format(emailData) html = self.getConfig(bodyHtmlCfg).format(emailData) msg = Message(recipients=[recipient], body=text, html=html, subject=self.getConfig(subjectCfg), sender=self.getConfig('SERVER_EMAIL_ADDRESS')) try: self.mail.send(msg) except SMTPException as e: if rmuser: user.rm() raise ReportedError("{0}: {1}".format(exceptionSendingEmail, e)) # @UndefinedVariable
def new(cls, user, credentialType, identifier, secret): oldcred = cls.get(credentialType, identifier) if oldcred is not None: raise ReportedError('Already existing credential', 400) cred = cls(user, credentialType, identifier, secret) cred.save() return cred
def setCanEmail(self, appName, user, value): app = Application.find(appName) if app == None: raise ReportedError(Messages.unknownApplication) theMap = AppMap.get(app, user) theMap.can_email = value theMap.save()
def new(cls, email, digest=None): u = cls.getByEmail(email) if u is not None: raise ReportedError([thereIsAlreadyAUserWithThatEmail]) user = cls(email, digest) user.save() return user
def authenticateUserOrBearer(self): authHeader = self.getHeader('Authorization') current_user = self.getCurrentUser() if current_user.is_authenticated: self.setAuthUser(current_user.userid, current_user.userid) elif authHeader: headerSplit = authHeader.split(" ") if len(headerSplit)!= 2: raise ReportedError([badAuthHeader,authHeader], status=403) token = headerSplit[1] tokeninfo = TokenInfoByAccessKey.find(token).tokeninfo appid = tokeninfo.client_id targetuserid = tokeninfo.user_id self.setAuthUser(targetuserid, appid) else: raise ReportedError([noAuthorization], status=403)
def validate_client_id(self, client_id, message=unauthorizedClient, errorCode=302, uri=None): app = Application.get(client_id) if self.isEmpty(app): raise ReportedError(unauthorizedClient, errorCode, uri=uri)
def getIdentifier(self, cert): try: cn = cert.get_subject().commonName digest = self.getDigest(cert) identifier = "{0}/{1}".format(cn, digest) return identifier except: raise ReportedError(errorInCert)
def test_reportedError_logs(self): try: raise ReportedError("test") except ReportedError: raisePoint = Decorators.getRaisePoint() self.assertTrue('in test_reportedError_logs' in raisePoint, "raisePoint problem {0}".format(raisePoint)) self.assertTrue('raise ReportedError("test")' in raisePoint, "raisePoint problem2 {0}".format(raisePoint))
def registerCertUser(self, email, identifier, digest, cred): if email is None: raise ReportedError([youHaveToRegisterFirst], 403) theEmail = email[0] CredentialManager.create_user_with_creds("certificate", identifier, digest, theEmail) cred = Credential.get("certificate", identifier) self.sendPasswordVerificationEmail(cred.user) return cred
def doChangePassword(self, form): user = self.getCurrentUser() cred = Credential.getByUser(user, 'password') oldSecret = CredentialManager.protect_secret(form.oldPassword.data) if cred.secret != oldSecret: raise ReportedError([oldPasswordDoesNotMatch]) secret = CredentialManager.protect_secret(form.newPassword.data) cred.secret = secret cred.save() return self.simple_response(passwordChangedSuccessfully)
def loginOrRegisterCertUser(self, cert, email): if cert is None or cert == '': raise ReportedError([noCertificateGiven], 403) identifier = self.getIdentifier(cert) cred = Credential.get("certificate", identifier) if cred is None: digest = self.getDigest(cert) cred = self.registerCertUser(email, identifier, digest, cred) cred.user.activate() return cred
def getUserForEmailAndOrHash(self, digest: Digest, email: Union[str,None]): if email: user = User.getByEmail(email) if user is None: raise ReportedError([noSuchUser], 400) self.checkUserAgainsDigest(digest, user) return user users = User.getByDigest(digest) self.assureExactlyOneUserInList(users) return users[0]
def signRequest(self, form): try: cert = self.createCertFromReq(form.pubkey.data, form.email.data) except Exception: raise ReportedError(errorInCert) user = self.getCurrentUser() if user.is_authenticated: self.addCertCredentialToUser(cert, user) else: self.registerAndLoginCertUser(form, cert) return self.createCertResponse(cert)
def doSslLogin(self): certtext = self.getEnvironmentVariable('SSL_CLIENT_CERT') try: cert = crypto.load_certificate(crypto.FILETYPE_PEM, certtext) except: raise ReportedError(errorInCert) email = self.getEmailFromQueryParameters() cred = self.loginOrRegisterCertUser(cert, email) resp = self.finishLogin(cred) resp.headers['Access-Control-Allow-Origin'] = "*" return resp
def findTemporaryEmailCredential(self, secret): cred = Credential.getBySecret("changeemail", secret) verify = False if cred is None: credverify = Credential.getBySecret("changeemailandverify", secret) if credverify is None: raise ReportedError(badChangeEmailSecret, 403) else: cred = credverify verify = True return cred, verify
def refresh_token(self, form): self.validateRefreshTokenParameters(form) keyData = self.from_refresh_token(form) if self.isEmpty(keyData): raise ReportedError(invalidGrant, 400) keyData.rm() return self.persistAndRespond(form.client_id.data, keyData.user_id)
def doPasswordReset(self, form): Credential.deleteExpired(self.passwordResetCredentialType) cred = Credential.getBySecret( self.passwordResetCredentialType, form.secret.data) if cred is None or (cred.getExpirationTime() < time.time()): raise ReportedError([theSecretHasExpired], 404) passcred = Credential.getByUser(cred.user, 'password') protectedSecret = CredentialManager.protect_secret(form.password.data) if not passcred: passcred = Credential.new(cred.user, "password", cred.user.email, protectedSecret) else: passcred.secret = protectedSecret cred.rm() return self.simple_response(passwordSuccessfullyChanged)
def checkHashInOtherUsers(self, user: User, additionalInfo: dict, digest: Digest) -> None: if digest is None: return anotherUsers = User.getByDigest(digest) assuredCollision = False if anotherUsers: for aUser in anotherUsers: if self.handAssured(aUser): self.sendHashCollisionMail(aUser, assured=True, inAssurance=False) assuredCollision = True else: self.sendHashCollisionMail(aUser, assured=False, inAssurance=False) if assuredCollision: raise ReportedError([anotherUserUsingYourHash]) additionalInfo["message"] = anotherUserUsingYourHash
def deleteDigestFromOtherUsers(self, user: User) -> int: digest = user.hash numOfOthers = 0 assuredCollision = False if digest: users = User.getByDigest(digest) for anotherUser in users: if anotherUser.email != user.email: anotherUser.hash = None anotherUser.save() numOfOthers += 1 if self.handAssured(anotherUser): self.sendHashCollisionMail(anotherUser, assured=True, inAssurance=True) assuredCollision = True if assuredCollision: message = [otherUsersWithYourHash, numOfOthers] raise ReportedError(message) return numOfOthers
def emailChangeInit(self, newEmailAddress, user): if User.getByEmail(newEmailAddress): raise ReportedError(thereIsAlreadyAUserWithThatEmail, 418) secret, expiry = CredentialManager.createTemporaryCredential( user, "changeemail", additionalInfo=newEmailAddress) self.sendEmail(user, secret, expiry, "CHANGE_EMAIL_OLD", newemail=newEmailAddress, oldemail=user.email) secret, expiry = CredentialManager.createTemporaryCredential( user, "changeemailandverify", additionalInfo=newEmailAddress) self.sendEmail(user, secret, expiry, "CHANGE_EMAIL_NEW", recipient=newEmailAddress, newemail=newEmailAddress, oldemail=user.email) Credential.deleteExpired("changeemail") Credential.deleteExpired("changeemailandverify")
def validate_access(self, uri): if not self.getCurrentUser().is_authenticated: raise ReportedError(accessDenied, 302, uri=self.app.config.get('LOGIN_URL'))
def validate_scope(self, client_id, scope, errorCode=302, uri=None): if not scope == "": raise ReportedError(invalidScope, errorCode, uri=uri)