Python flask_principal.Identity() Examples
The following are 30
code examples of flask_principal.Identity().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
flask_principal
, or try the search function
.
Example #1
Source File: decorators.py From flask-security with MIT License | 6 votes |
def _check_token(): # N.B. this isn't great Flask-Login 0.5.0 made this protected # Issue https://github.com/maxcountryman/flask-login/issues/471 # was filed to restore public access. We want to call this via # login_manager in case someone has overridden the login_manager which we # allow. if hasattr(_security.login_manager, "request_callback"): # Pre 0.5.0 user = _security.login_manager.request_callback(request) else: user = _security.login_manager._request_callback(request) if user and user.is_authenticated: app = current_app._get_current_object() _request_ctx_stack.top.user = user identity_changed.send(app, identity=Identity(user.fs_uniquifier)) return True return False
Example #2
Source File: views.py From gitmark with GNU General Public License v2.0 | 6 votes |
def post(self): if request.form.get('login_github'): session['oauth_callback_type'] = 'login' return github_auth.github_auth() # return 'login_github' form = forms.LoginForm(obj=request.form) if form.validate(): try: user = models.User.objects.get(username=form.username.data) except models.User.DoesNotExist: user = None if user and user.verify_password(form.password.data): login_user(user, form.remember_me.data) user.last_login = datetime.datetime.now user.save() identity_changed.send(current_app._get_current_object(), identity=Identity(user.username)) return redirect(request.args.get('next') or url_for('main.index')) flash('Invalid username or password', 'danger') return self.get(form=form)
Example #3
Source File: __init__.py From zou with GNU Affero General Public License v3.0 | 6 votes |
def configure_auth(): from zou.app.services import persons_service @jwt.token_in_blacklist_loader def check_if_token_is_revoked(decrypted_token): return auth_tokens_store.is_revoked(decrypted_token) @jwt.user_loader_callback_loader def add_permissions(callback): try: user = persons_service.get_current_user() if user is not None: identity_changed.send( current_app._get_current_object(), identity=Identity(user["id"]), ) return user except PersonNotFoundException: return None
Example #4
Source File: auth.py From flaskapp with MIT License | 6 votes |
def login(): """GET|POST /login: login form handler """ form = LoginForm() if form.validate_on_submit(): # login user u = User.query.filter(User.email == form.email.data).first() login_user(u, remember=form.remember_me.data) # tell flask-principal the identity changed identity_changed.send(current_app._get_current_object(), identity=Identity(u.id)) return redirect(request.args.get('next') or url_for('content.home')) return render_template('/auth/login.html', form=form)
Example #5
Source File: auth.py From flaskapp with MIT License | 6 votes |
def create_account(): """GET|POST /create-account: create account form handler """ form = CreateAccountForm() if form.validate_on_submit(): # add user to database u = User(email=form.email.data, password=generate_password_hash(form.password.data)) db.session.add(u) db.session.flush() # send verification email send_verification_email(u) # login user login_user(u, remember=True) identity_changed.send(current_app._get_current_object(), identity=Identity(u.id)) return redirect(request.args.get('next') or url_for('content.home')) return render_template('/auth/create-account.html', form=form)
Example #6
Source File: auth_context_type.py From quay with Apache License 2.0 | 6 votes |
def identity(self): """ Returns the identity for the auth context. """ if self.oauthtoken: scope_set = scopes_from_scope_string(self.oauthtoken.scope) return QuayDeferredPermissionUser.for_user(self.oauthtoken.authorized_user, scope_set) if self.authed_user: return QuayDeferredPermissionUser.for_user(self.authed_user) if self.token: return Identity(self.token.get_code(), "token") if self.signed_data: identity = Identity(None, "signed_grant") identity.provides.update(self.signed_data["grants"]) return identity return None
Example #7
Source File: security.py From flask-unchained with MIT License | 5 votes |
def _identity_loader(self) -> Union[Identity, None]: """ Identity loading function to be passed to be assigned to the Principal instance returned by :meth:`_get_principal`. """ if not isinstance(current_user._get_current_object(), AnonymousUser): return Identity(current_user.id)
Example #8
Source File: login.py From flicket with MIT License | 5 votes |
def login(): # if the user is already logged in redirect to homepage. if g.user is not None and g.user.is_authenticated: return redirect(url_for('flicket_bp.index')) # load the LogInForm from forms.py form = LogInForm() if form.validate_on_submit(): user = FlicketUser.query.filter( or_(FlicketUser.username == form.username.data, func.lower(FlicketUser.email) == form.username.data.lower())).first() identity_changed.send(app, identity=Identity(user.id)) login_user(user, remember=form.remember_me.data) # set the user token, authentication token is required for api use. user.get_token() db.session.commit() if user.email is None or user.email == '': flash(gettext('Please set your email and job title.'), category='danger') return redirect(url_for('flicket_bp.user_details')) else: flash(gettext('You were logged in successfully.'), category='success') return redirect(url_for('flicket_bp.index')) return render_template('flicket_login.html', title='Log In', form=form) # logout page
Example #9
Source File: security.py From flask-unchained with MIT License | 5 votes |
def _on_identity_loaded(self, sender, identity: Identity) -> None: """ Callback that runs whenever a new identity has been loaded. """ if hasattr(current_user, 'id'): identity.provides.add(UserNeed(current_user.id)) for role in getattr(current_user, 'roles', []): identity.provides.add(RoleNeed(role.name)) identity.user = current_user
Example #10
Source File: test_v2_tuf.py From quay with Apache License 2.0 | 5 votes |
def admin_identity(namespace, reponame): identity = Identity("admin") identity.provides.add(permissions._RepositoryNeed(namespace, reponame, "admin")) identity.provides.add(permissions._OrganizationRepoNeed(namespace, "admin")) return identity
Example #11
Source File: test_v2_tuf.py From quay with Apache License 2.0 | 5 votes |
def write_identity(namespace, reponame): identity = Identity("writer") identity.provides.add(permissions._RepositoryNeed(namespace, reponame, "write")) identity.provides.add(permissions._OrganizationRepoNeed(namespace, "write")) return identity
Example #12
Source File: test_v2_tuf.py From quay with Apache License 2.0 | 5 votes |
def read_identity(namespace, reponame): identity = Identity("reader") identity.provides.add(permissions._RepositoryNeed(namespace, reponame, "read")) identity.provides.add(permissions._OrganizationRepoNeed(namespace, "read")) return identity
Example #13
Source File: shared.py From quay with Apache License 2.0 | 5 votes |
def conduct_call( client, resource, url_for, method, params, body=None, expected_code=200, headers=None, raw_body=None, ): """ Conducts a call to a Flask endpoint. """ params = add_csrf_param(client, params) final_url = url_for(resource, **params) headers = headers or {} headers.update({"Content-Type": "application/json"}) if body is not None: body = json.dumps(body) if raw_body is not None: body = raw_body # Required for anonymous calls to not exception. g.identity = Identity(None, "none") rv = client.open(final_url, method=method, data=body, headers=headers) msg = "%s %s: got %s expected: %s | %s" % ( method, final_url, rv.status_code, expected_code, rv.data, ) assert rv.status_code == expected_code, msg return rv
Example #14
Source File: permissions.py From quay with Apache License 2.0 | 5 votes |
def on_identity_loaded(sender, identity): logger.debug("Identity loaded: %s" % identity) # We have verified an identity, load in all of the permissions if isinstance(identity, QuayDeferredPermissionUser): logger.debug("Deferring permissions for user with uuid: %s", identity.id) elif identity.auth_type == "user_uuid": logger.debug("Switching username permission to deferred object with uuid: %s", identity.id) switch_to_deferred = QuayDeferredPermissionUser.for_id(identity.id) identity_changed.send(app, identity=switch_to_deferred) elif identity.auth_type == "token": logger.debug("Loading permissions for token: %s", identity.id) token_data = model.token.load_token_data(identity.id) repo_grant = _RepositoryNeed( token_data.repository.namespace_user.username, token_data.repository.name, token_data.role.name, ) logger.debug("Delegate token added permission: %s", repo_grant) identity.provides.add(repo_grant) elif identity.auth_type == "signed_grant" or identity.auth_type == "signed_jwt": logger.debug("Loaded %s identity for: %s", identity.auth_type, identity.id) else: logger.error("Unknown identity auth type: %s", identity.auth_type)
Example #15
Source File: registry_jwt_auth.py From quay with Apache License 2.0 | 5 votes |
def process_registry_jwt_auth(scopes=None): """ Processes the registry JWT auth token found in the authorization header. If none found, no error is returned. If an invalid token is found, raises a 401. """ def inner(func): @wraps(func) def wrapper(*args, **kwargs): logger.debug("Called with params: %s, %s", args, kwargs) auth = request.headers.get("authorization", "").strip() if auth: try: extracted_identity, context_dict = identity_from_bearer_token(auth) identity_changed.send(app, identity=extracted_identity) logger.debug("Identity changed to %s", extracted_identity.id) auth_context = SignedAuthContext.build_from_signed_dict(context_dict) if auth_context is not None: logger.debug("Auth context set to %s", auth_context.signed_data) set_authenticated_context(auth_context) except InvalidJWTException as ije: repository = None if "namespace_name" in kwargs and "repo_name" in kwargs: repository = kwargs["namespace_name"] + "/" + kwargs["repo_name"] abort( 401, message=str(ije), headers=get_auth_headers(repository=repository, scopes=scopes), ) else: logger.debug("No auth header.") return func(*args, **kwargs) return wrapper return inner
Example #16
Source File: auth_provider.py From knowledge-repo with Apache License 2.0 | 5 votes |
def _perform_login(self, user): user = prepare_user(user) login_user(user) # Notify flask principal that the identity has changed identity_changed.send(current_app._get_current_object(), identity=Identity(user.id))
Example #17
Source File: models.py From maple-bbs with GNU General Public License v3.0 | 5 votes |
def login(self, remember=True): login_user(self, remember) identity_changed.send( current_app._get_current_object(), identity=Identity(self.id))
Example #18
Source File: login.py From FlowKit with Mozilla Public License 2.0 | 5 votes |
def signin(): json = request.get_json() if "username" not in json or "password" not in json: raise InvalidUsage("Must supply username or password.") user = User.query.filter(User.username == json["username"]).first() if user is not None: current_app.logger.debug( "Login attempt", username=user.username, user_id=user.id ) if user.is_correct_password(json["password"]): two_factor = user.two_factor_auth if two_factor is not None and two_factor.enabled: if "two_factor_code" not in json or json["two_factor_code"] == "": raise InvalidUsage( "Must supply a two-factor authentication code.", payload={"need_two_factor": True}, ) try: two_factor.validate(json["two_factor_code"]) except (Unauthorized, binascii.Error): two_factor.validate_backup_code(json["two_factor_code"]) login_user(user, remember=False) identity_changed.send( current_app._get_current_object(), identity=Identity(user.id) ) session.modified = True return jsonify( { "logged_in": True, "is_admin": user.is_admin, "require_two_factor_setup": current_user.two_factor_setup_required, } ) current_app.logger.debug("Failed login attempt", username=json["username"]) raise Unauthorized("Incorrect username or password.")
Example #19
Source File: api.py From spkrepo with MIT License | 5 votes |
def api_auth_required(f): @wraps(f) def wrapper(*args, **kwargs): if request.authorization and request.authorization.type == "basic": user = user_datastore.find_user(api_key=request.authorization.username) if user and user.has_role("developer"): _request_ctx_stack.top.user = user identity_changed.send( current_app._get_current_object(), identity=Identity(user.id) ) return f(*args, **kwargs) abort(401) return wrapper
Example #20
Source File: auth_required.py From flask-unchained with MIT License | 5 votes |
def _check_token(): user = security.login_manager._request_callback(request) if user and user.is_authenticated: _request_ctx_stack.top.user = user identity_changed.send(current_app._get_current_object(), identity=Identity(user.id)) return True return False
Example #21
Source File: conftest.py From lemur with Apache License 2.0 | 5 votes |
def logged_in_user(session, app): with app.test_request_context(): identity_changed.send(current_app._get_current_object(), identity=Identity(1)) yield
Example #22
Source File: cli.py From lemur with Apache License 2.0 | 5 votes |
def request_reissue(certificate, commit): """ Reissuing certificate and handles any exceptions. :param certificate: :param commit: :return: """ status = FAILURE_METRIC_STATUS try: print("[+] {0} is eligible for re-issuance".format(certificate.name)) # set the lemur identity for all cli commands identity_changed.send(current_app._get_current_object(), identity=Identity(1)) details = get_certificate_primitives(certificate) print_certificate_details(details) if commit: new_cert = reissue_certificate(certificate, replace=True) print("[+] New certificate named: {0}".format(new_cert.name)) status = SUCCESS_METRIC_STATUS except Exception as e: sentry.captureException(extra={"certificate_name": str(certificate.name)}) current_app.logger.exception( f"Error reissuing certificate: {certificate.name}", exc_info=True ) print(f"[!] Failed to reissue certificate: {certificate.name}. Reason: {e}") metrics.send( "certificate_reissue", "counter", 1, metric_tags={"status": status, "certificate": certificate.name}, )
Example #23
Source File: auth.py From flaskapp with MIT License | 5 votes |
def reset_password(): """GET /reset-password: choose new password """ # get password-reset entry f = (PasswordResetRequest.key == request.args.get('key'), User.email == request.args.get('email')) r = PasswordResetRequest.query.filter(*f).first() # return error response if link doesn't exist or wrong email if r == None or r.user.email != request.args['email']: return render_template('/auth/reset-password-error.html'), 400 # expired if older than 1 day delta = datetime.datetime.utcnow() - r.create_ts if delta.days > 0: db.session.delete(r) db.session.flush() return render_template('/auth/reset-password-error.html'), 400 # handle form form = ResetPasswordForm() if form.validate_on_submit(): # save new password u = r.user u.password = generate_password_hash(form.password.data) db.session.add(u) # login user login_user(u, remember=True) identity_changed.send(current_app._get_current_object(), identity=Identity(u.id)) # delete password reset db.session.delete(r) db.session.flush() return render_template('/auth/reset-password-followup.html') return render_template('/auth/reset-password.html', form=form)
Example #24
Source File: core.py From flask-security with MIT License | 5 votes |
def _identity_loader(): if not isinstance(current_user._get_current_object(), AnonymousUserMixin): identity = Identity(current_user.fs_uniquifier) return identity
Example #25
Source File: utils.py From flask-security with MIT License | 5 votes |
def _(translate): """Identity function to mark strings for translation.""" return translate
Example #26
Source File: decorators.py From flask-security with MIT License | 5 votes |
def _check_http_auth(): auth = request.authorization or BasicAuth(username=None, password=None) if not auth.username: return False user = find_user(auth.username) if user and user.verify_and_update_password(auth.password): _security.datastore.commit() app = current_app._get_current_object() _request_ctx_stack.top.user = user identity_changed.send(app, identity=Identity(user.fs_uniquifier)) return True return False
Example #27
Source File: cloud.py From AstroBox with GNU Affero General Public License v3.0 | 4 votes |
def signinWithKey(self, email, private_key, hasSessionContext = True): from octoprint.server import userManager user = None userLoggedIn = False online = networkManager().isOnline() if online: public_key = self.get_public_key(email, private_key) if public_key: #Let's protect the box now: user = userManager.findUser(email) if user and user.has_password(): userManager.changeCloudAccessKeys(email, public_key, private_key) else: self._logger.info("New user signing requires password method") return False userLoggedIn = True else: user = userManager.findUser(email) userLoggedIn = user and user.check_privateKey(private_key) if userLoggedIn: if hasSessionContext: login_user(user, remember=True) userId = user.get_id() self.settings.set(["cloudSlicer", "loggedUser"], userId) self.settings.save() boxrouterManager().boxrouter_connect() if hasSessionContext: identity_changed.send(current_app._get_current_object(), identity=Identity(userId)) #let the singleton be recreated again, so new credentials are taken into use global _instance _instance = None eventManager().fire(Events.LOCK_STATUS_CHANGED, userId) return True elif not online: raise AstroPrintCloudNoConnectionException() return False
Example #28
Source File: cloud.py From AstroBox with GNU Affero General Public License v3.0 | 4 votes |
def signin(self, email, password, hasSessionContext = True): from octoprint.server import userManager user = None userLoggedIn = False online = networkManager().isOnline() if online: data_private_key = self.get_private_key(email, password) if data_private_key: private_key = data_private_key['private_key'] public_key = self.get_public_key(email, private_key) orgId = data_private_key['organization_id'] groupId = data_private_key['group_id'] if public_key: #Let's protect the box now: #We need to keep this code for a while, or it can generate errors it the user who is loging whast loged before user = userManager.findUser(email) if user: userManager.changeUserPassword(email, password) userManager.changeCloudAccessKeys(email, public_key, private_key, orgId, groupId) else: user = userManager.addUser(email, password, public_key, private_key, orgId, groupId, True) userLoggedIn = True else: user = userManager.findUser(email) userLoggedIn = user and user.check_password(userManager.createPasswordHash(password)) if userLoggedIn: if hasSessionContext: login_user(user, remember=True) userId = user.get_id() self.settings.set(["cloudSlicer", "loggedUser"], userId) self.settings.save() boxrouterManager().boxrouter_connect() if hasSessionContext: identity_changed.send(current_app._get_current_object(), identity=Identity(userId)) #let the singleton be recreated again, so new credentials are taken into use global _instance _instance = None eventManager().fire(Events.LOCK_STATUS_CHANGED, userId) return True elif not online: raise AstroPrintCloudNoConnectionException() return False
Example #29
Source File: __init__.py From AstroBox with GNU Affero General Public License v3.0 | 4 votes |
def login(): if octoprint.server.userManager is not None and "user" in request.values.keys() and "pass" in request.values.keys(): username = request.values["user"] password = request.values["pass"] if "remember" in request.values.keys() and request.values["remember"] == "true": remember = True else: remember = False user = octoprint.server.userManager.findUser(username) if user is not None: if user.has_password(): if astroprintCloud().validatePassword(username, password): login_user(user, remember=remember) identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id())) return jsonify(user.asDict()) else : try: if astroprintCloud().signin(username, password): return jsonify(current_user) except (AstroPrintCloudNoConnectionException, ConnectionError): return make_response(("AstroPrint.com can't be reached", 503, [])) except (AstroPrintCloudInsufficientPermissionsException): return make_response(("Insuficient permissions", 403, [])) return make_response(("User unknown or password incorrect", 401, [])) elif "passive" in request.values.keys(): user = current_user if user is not None and not user.is_anonymous: identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id())) return jsonify(user.asDict()) elif s().getBoolean(["accessControl", "autologinLocal"]) \ and s().get(["accessControl", "autologinAs"]) is not None \ and s().get(["accessControl", "localNetworks"]) is not None: autologinAs = s().get(["accessControl", "autologinAs"]) localNetworks = netaddr.IPSet([]) for ip in s().get(["accessControl", "localNetworks"]): localNetworks.add(ip) try: remoteAddr = util.getRemoteAddress(request) if netaddr.IPAddress(remoteAddr) in localNetworks: user = octoprint.server.userManager.findUser(autologinAs) if user is not None: login_user(user) identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id())) return jsonify(user.asDict()) except: logger = logging.getLogger(__name__) logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks)) return NO_CONTENT
Example #30
Source File: util.py From AstroBox with GNU Affero General Public License v3.0 | 4 votes |
def restricted_access(func, apiEnabled=True): """ If you decorate a view with this, it will ensure that first setup has been done for AstroBox's Access Control plus that any conditions of the login_required decorator are met. It also allows to login using the masterkey or any of the user's apikeys if API access is enabled globally and for the decorated view. If AstroBox's Access Control has not been setup yet (indicated by the "firstRun" flag from the settings being set to True and the userManager not indicating that it's user database has been customized from default), the decorator will cause a HTTP 403 status code to be returned by the decorated resource. If an API key is provided and it matches a known key, the user will be logged in and the view will be called directly. If the provided key doesn't match any known key, a HTTP 403 status code will be returned by the decorated resource. Otherwise the result of calling login_required will be returned. """ @wraps(func) def decorated_view(*args, **kwargs): # if AstroBox hasn't been set up yet, abort if settings().getBoolean(["server", "firstRun"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()): return make_response("AstroBox isn't setup yet", 403) # if API is globally enabled, enabled for this request and an api key is provided that is not the current UI API key, try to use that apikey = getApiKey(request) if settings().get(["api", "enabled"]) and apiEnabled and apikey is not None: if apikey != octoprint.server.UI_API_KEY: if apikey == settings().get(["api", "key"]): # master key was used user = ApiUser() else: # user key might have been used user = octoprint.server.userManager.findUser(apikey=apikey) if user is None: return make_response("Invalid API key", 401) if login_user(user, remember=False): identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id())) return func(*args, **kwargs) else: return func(*args, **kwargs) return make_response("Invalid Api Key or API Disabled", 401) return decorated_view