def oauth_callback(provider): if not current_user.is_anonymous: return redirect(url_for('public.index')) oauth = OAuthSignIn.get_provider(provider) social_id, username, email,jmeno,prijmeni,profile_url,image_url= oauth.callback() if social_id is None: flash('Authentication failed.') return redirect(url_for('public.index')) ouser = Oauth.query.filter_by(social_id=social_id).first() #if email is None: # flash(gettext('We need your email!'), 'warning') # return redirect(request.args.get('next') or g.lang_code + '/index') user = User.find_by_email(email) if user is None: user = User.create( username=social_id, email=email, password=social_id, remote_addr=request.remote_addr, jmeno=jmeno, prijmeni=prijmeni ) if not ouser: ouser = Oauth( user_id=user.id,social_id=social_id, nickname=username, email=email,jmeno=jmeno,prijmeni=prijmeni,profile_url=profile_url,image_url=image_url) ouser.save() login_user(user, True) return redirect(url_for('public.index'))
class EditForm(Form): first_name = StringField('Voornaam') last_name = StringField('Achternaam') username = StringField('Gebruiksernaam', render_kw={'readonly': ''}) email = StringField('Email') level = SelectField('Niveau', validators=[DataRequired()], choices=User.get_zipped_levels()) user_type = SelectField('Type', validators=[DataRequired()], choices=User.get_zipped_types()) change_password=SelectField('Paswoord aanpassen', choices=[('False', 'Neen'), ('True', 'Ja')]) password = PasswordField('Paswoord') confirm_password = PasswordField('Bevestig Paswoord') def validate_password(self, field): if self.user_type.data == User.USER_TYPE.LOCAL: if self.change_password.data == 'True': if field.data == '': raise ValidationError('Paswoord invullen aub') else: field.data = None else: field.data = None def validate_confirm_password(self, field): if self.user_type.data == User.USER_TYPE.LOCAL and self.password.data: if field.data != self.password.data: raise ValidationError('Beide paswoorden moeten hetzelfde zijn') else: field.data = None
def oauth_callback(provider): if not current_user.is_anonymous: return redirect(url_for('public.index')) oauth = OAuthSignIn.get_provider(provider) social_id, username, email, jmeno, prijmeni, profile_url, image_url = oauth.callback( ) if social_id is None: flash('Authentication failed.') return redirect(url_for('public.index')) ouser = Oauth.query.filter_by(social_id=social_id).first() #if email is None: # flash(gettext('We need your email!'), 'warning') # return redirect(request.args.get('next') or g.lang_code + '/index') user = User.find_by_email(email) if user is None: user = User.create(username=social_id, email=email, password=social_id, remote_addr=request.remote_addr, jmeno=jmeno, prijmeni=prijmeni) if not ouser: ouser = Oauth(user_id=user.id, social_id=social_id, nickname=username, email=email, jmeno=jmeno, prijmeni=prijmeni, profile_url=profile_url, image_url=image_url) ouser.save() login_user(user, True) return redirect(url_for('public.index'))
def signup() -> Union[Tuple[Response, int, Dict[str, str]], Tuple[str, int]]: """ Signup new user """ try: if not request.json or not 'email_id' in request.json \ or not 'password' in request.json: return bad_request('Email_id and/or password is missing!') email = request.json.get('email_id') password = request.json.get('password') user = User(email=email, password=password) db.session.add(user) db.session.commit() auth_token = user.encode_auth_token(user.id) responseObj = { 'status': 'Success', 'message': 'Successfully signed up.', 'auth_token': auth_token.decode('utf-8') } return jsonify(responseObj), 201, {'Content-Type': 'application/json'} except Exception as ex: print(ex) return 'try again', 401
class ViewForm(Form): first_name = StringField('Voornaam', render_kw={'disabled': ''}) last_name = StringField('Achternaam', render_kw={'disabled': ''}) username = StringField('Gebruiksernaam', render_kw={'readonly': ''}) email = StringField('Email', render_kw={'disabled': ''}) level = SelectField('Niveau', render_kw={'disabled': ''}, choices=User.get_zipped_levels()) user_type = SelectField('Type', render_kw={'disabled': ''}, choices=User.get_zipped_types())
def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('Congratulations, you are now a registered user!') return redirect(url_for('auth.login')) return render_template('register.html', title='Register', form=form)
def fake_user(): return User(fake.word() + fake.word(), fake.email(), fake.name().split(' ')[0], fake.word(), password=fake.word(), remote_addr=fake.ipv4(network=False), active=True)
def setUp(self): self.app = create_app(config_name='testing') self.daoManager = DAOManagerSqlite() create_tables(self.daoManager.conecction.cursor(), 'app/schema.sql') for i in range(10): user = User('Alvaro{}'.format(i), 'Niño', '16/12/19', '*****@*****.**') self.daoManager.do(DAOManager.USER, DAOManager.CREATE, user) self.daoManager.commit()
def create_admin(): try: from app.data.models import User find_admin = User.query.filter(User.username == 'admin').first() if not find_admin: admin = User(username='******', password='******', level=User.LEVEL.ADMIN, user_type=User.USER_TYPE.LOCAL) db.session.add(admin) db.session.commit() except Exception as e: log.warning('database does not exist yet')
def test_user_transaction(self): resL = [] self.daoManager.beginTransaction() # create user user = User('AlvaroCre', 'Niño', '12-12/19', '*****@*****.**') resL.append( self.daoManager.do(DAOManager.USER, DAOManager.CREATE, user)) # update user user = User('AlvaroUpdate', 'Niño', '12/12/19', '*****@*****.**') user.id = 2 resL.append( self.daoManager.do(DAOManager.USER, DAOManager.UPDATE, user)) state = reduce(lambda a, b: a and b, resL) res = self.daoManager.endTransaction(state) self.assertFalse(res)
def create_admin(): from app.data.models import User find_admin = User.query.filter(User.username == 'admin').first() if not find_admin: admin = User(username='******', password='******', level=User.LEVEL.ADMIN, user_type=User.USER_TYPE.LOCAL) db.session.add(admin) db.session.commit()
def login_dashboard(): if 'version' in request.args: profile = json.loads(request.args['profile']) if not 'username' in profile: # not good log.error(u'Smartschool geeft een foutcode terug: {}'.format( profile['error'])) return redirect(url_for('auth.login')) if profile['basisrol'] in SMARTSCHOOL_ALLOWED_BASE_ROLES: # Students are NOT allowed to log in user = User.query.filter_by( username=func.binary(profile['username']), user_type=User.USER_TYPE.OAUTH).first() if user: user.first_name = profile['name'] user.last_name = profile['surname'] user.email = profile['email'] else: user = User(username=profile['username'], first_name=profile['name'], last_name=profile['surname'], email=profile['email'], user_type=User.USER_TYPE.OAUTH, level=User.LEVEL.USER) db.session.add(user) db.session.flush() # user.id is filled in user.last_login = datetime.datetime.now() login_user(user) log.info(u'OAUTH user {} logged in'.format(user.username)) try: db.session.commit() except Exception as e: log.error(u'Could not save user : {}'.format(e)) return redirect(url_for('auth.login')) # Ok, continue return redirect(url_for('registration.show')) else: redirect_uri = f'{flask_app.config["SMARTSCHOOL_OUATH_REDIRECT_URI"]}/dashboard' return redirect( f'{flask_app.config["SMARTSCHOOL_OAUTH_SERVER"]}?app_uri={redirect_uri}' )
def facebook_logged_in(facebook_blueprint, token): if not token: flash("Failed to log in with facebook.", category="error") return False resp = facebook_blueprint.session.get( "me?fields=id,name,email,gender,picture,locale") if not resp.ok: msg = "Failed to fetch user info from facebook." flash(msg, category="error") return False facebook_info = resp.json() facebook_user_id = str(facebook_info["id"]) # Find this OAuth token in the database, or create it query = OAuth.query.filter_by( provider=facebook_blueprint.name, provider_user_id=facebook_user_id, ) try: oauth = query.one() except NoResultFound: oauth = OAuth( provider=facebook_blueprint.name, provider_user_id=facebook_user_id, token=token, ) if oauth.user: login_user(oauth.user) flash("Successfully signed in with GitHub.") else: # Create a new local user account for this user user = User( # Remember that `email` can be None, if the user declines # to publish their email address on GitHub! email=facebook_info["email"], username=facebook_info["name"], ) # Associate the new local user account with the OAuth token oauth.user = user # Save and commit our database models db.session.add_all([user, oauth]) db.session.commit() # Log in the new local user account login_user(user) flash("Successfully signed in with GitHub.") # Disable Flask-Dance's default behavior for saving the OAuth token return False
def profile_edit(): form = EditProfileForm(obj=current_user) if form.validate_on_submit(): if User.if_exists_email(form.email._value()) and current_user.email!=form.email._value(): flash(gettext("An account has already been registered with that email. Try another?"), 'warning') return render_template('profile-edit.html', form=form, user=current_user) if not current_user.username == form.username._value(): flash(gettext("You little rebel! I like you!"), 'warning') return render_template('profile-edit.html', form=form, user=current_user) form.populate_obj(current_user) current_user.commit() flash(gettext('User {username} edited').format(username=current_user.username),'success') return render_template('profile-edit.html', form=form, user=current_user)
def group_edit_users_submit(): if request.method != "POST": return "Only POST requests allowed" data = json.loads(request.values.get('data')) userdata = [User.query.filter_by(id=row[0]).first() for row in data.get('data')] group = Group.query.filter_by(nazev=data.get('group')).first_or_404() userlist = User.find_in_group(group.id) for user in User.query.all(): if user in userlist and user not in userdata: group.remove_user(user) if user not in userlist and user in userdata: group.add_user(user) return "ok"
def dispatch(self, *args, **kwargs): self.gae_user = users.get_current_user() if users.is_oauth(): if users.get_client_id() not in _OAUTH_WHITELIST: logging.warning('OAuth consumer %s forbidden' % users.get_client_id()) self.abort(403) with Stopwatch.timer('userfetch'): self.user = User.get_current() try: super(RequestHandler, self).dispatch(*args, **kwargs) self.flush_stopwatch() except Exception: self.flush_stopwatch() raise
def item_add(done=False): try: common_details = tables.prepare_item_config_for_view( configuration, 'add') if done: form = AddForm(request.form) if form.validate() and request.method == 'POST': if form.user_type.data == User.USER_TYPE.LOCAL: password = form.password.data else: password = '' user = User(email=form.email.data, username=form.username.data, first_name=form.first_name.data, last_name=form.last_name.data, password=password, level=form.level.data, user_type=form.user_type.data) db.session.add(user) db.session.commit() log.info('add: {}'.format(user.log())) return redirect(url_for('user.show')) else: return render_template('user/user.html', form_details=form, common_details=common_details) else: form = AddForm() return render_template('user/user.html', form_details=form, common_details=common_details) except Exception as e: log.error(u'Could not add user {}'.format(e)) flash_plus(u'Kan gebruikers niet toevoegen', e) db.session.rollback() return redirect(url_for('user.show'))
def decorated(*args, **kwargs): token = None if 'x-access-token' in request.headers: token = request.headers['x-access-token'] if not token: return make_response( jsonify({'message': 'A valid token is missing'}), 401, {'Content-Type': 'application/json'}) try: data = User.decode_auth_token(token) if isinstance(data, int): return func(*args, **kwargs) else: return make_response(jsonify({'message': data}), 401, {'Content-Type': 'application/json'}) except: return make_response(jsonify({'message': 'Token is invalid'}), 401, {'Content-Type': 'application/json'})
def register(): form = RegisterUserForm() if form.validate_on_submit(): user = User.create(username=form.data['username'], email=form.data['email'], password=form.data['password'], remote_addr=request.remote_addr, jmeno=form.data['jmeno'], prijmeni=form.data['prijmeni']) s = URLSafeSerializer(current_app.secret_key) token = s.dumps(user.id) #send_registration_email.delay(user, token) #flash(gettext('Sent verification email to {email}').format(email=user.email),'success') flash( gettext('An account {username} has been created.').format( username=form.data['username'], ), 'success') return redirect(request.args.get('next') or g.lang_code + '/index') #return redirect(url_for('public.index')) return render_template('register.html', form=form)
def register(): form = RegisterUserForm() if form.validate_on_submit(): user = User.create( username=form.data['username'], email=form.data['email'], password=form.data['password'], remote_addr=request.remote_addr, jmeno=form.data['jmeno'], prijmeni=form.data['prijmeni'] ) s = URLSafeSerializer(current_app.secret_key) token = s.dumps(user.id) #send_registration_email.delay(user, token) #flash(gettext('Sent verification email to {email}').format(email=user.email),'success') flash(gettext('An account {username} has been created.').format(username=form.data['username'], ), 'success') return redirect(request.args.get('next') or g.lang_code + '/index') #return redirect(url_for('public.index')) return render_template('register.html', form=form)
def profile_edit(): form = EditProfileForm(obj=current_user) if form.validate_on_submit(): if User.if_exists_email(form.email._value( )) and current_user.email != form.email._value(): flash( gettext( "An account has already been registered with that email. Try another?" ), 'warning') return render_template('profile-edit.html', form=form, user=current_user) if not current_user.username == form.username._value(): flash(gettext("You little rebel! I like you!"), 'warning') return render_template('profile-edit.html', form=form, user=current_user) form.populate_obj(current_user) current_user.commit() flash( gettext('User {username} edited').format( username=current_user.username), 'success') return render_template('profile-edit.html', form=form, user=current_user)
def email_is_available(email): if not User.if_exists_email(email): return True return False
def create_user(name, username, email, password): """Create a new User instance """ return User(name, username, email, password)
def username_is_available(username): if not User.if_exists(username): return True return False
def load_user(id): return User.get_by_id(int(id))