def add_user(): try: email = request.form.get('email') password = request.form.get('password') client_id = request.form.get('client_id') try: client = Client.objects.get(client_id=client_id) except DoesNotExist: logging.info("Client not found.") return abort(400) if not client.has_password_credential_permission: return abort(400) salt = gen_salt(40) hashed_password = hashlib.sha512(password + salt).hexdigest() user = User( email=email, password=hashed_password, salt=salt ) user.save() return jsonify({"user": user.to_mongo()}) except NotUniqueError: logging.info("Duplicate user.") return abort(400) except TypeError: return abort(400) except Exception as e: logging.error(e.args[0]) return abort(500)
def signup(): if not missing_session(): return go_user_home() form = SignupForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, password=form.password.data) if form.avatar.data is not None: user.avatar = form.save_avatar() try: user.save() create_session(user) return redirect(url_for('user.profile', user_id=user.id)) except Exception as e: field = str(e).split('.')[2].split('[')[0] flash('Please choose a unique ' + field, 'error') return render_template('user/signup.html', form=form, session=session)
def register(): """ Register a new user with the backend Example: -------- curl -k -L -XPOST -i -H "Content-Type:application/x-www-form-urlencoded" -d "[email protected]&password=jay" https:/webpool.csf.asu.edu/pysalrest/user/register/ """ print request.form print type(request.form) email = request.form.get('email') password = request.form.get('password') name = email.split('@')[0] user = User(name=name, email=email) user.hashpwd(password) db.session.add(user) db.session.commit() token = user.generate_auth_token() uid = user.id return jsonify({ 'username': user.name, 'token': token.decode('ascii'), 'uid': uid })
def user_create(): req = request.get_json(force=True) user = User.query.filter_by(email=req['email']).first() # === request checking === # email used if user: return jsonify({'message': 'This email has been used'}), 400 # required fields if not req.keys() >= {'username', 'email', 'password'}: return jsonify({ 'message': 'Fields \'username\', \'email\' and \'password\' required' }), 400 user = User(username=req['username'], email=req['email']) user.set_password(req['password']) db.session.add(user) db.session.commit() res = make_response({'id': user.id, 'message': 'Success'}) return res, 200
def login(): form = LoginForm() if request.method == 'POST': if form.validate_on_submit(): email = request.form.get('email') password = request.form.get('password') token = api.get_token(email, password)['access_token'] res = api.get('/user/', token=token) user_id = res['user']['_id'] email = res['user']['email'] user = User(user_id) user.email = email session[str(user_id)] = user login_user(user) next = request.args.get('next') if not next_is_valid(next): return abort(401) return redirect(next or url_for('user.user')) return abort(400) return render_template('auth/login.html', form=form)
def load_user(username, password, client, request, *args, **kwargs): if re.match(r"[^@]+@[^@]+\.[^@]+", username): if not client.has_password_credential_permission: return None try: user = User.objects.get(email=username) except DoesNotExist: logging.info("User not found.") return None if not user.validate_password(password): return None return user elif username.isdigit(): if not client.has_facebook_credential_permission: return None try: facebook = Facebook(password) me = facebook.get('/me', params={'fields': 'id,name,email,link'}) except client.OAuthException: return None except Exception as e: logging.error(e) return None try: user = User.objects.get(facebook_id=username) user.facebook_access_token = password user.save() except DoesNotExist: facebook_id = me['id'] email = me['email'] name = me['name'] user = User( facebook_id=facebook_id, email=email, name=name, facebook_access_token=password, password=None, salt=None, ) user.save() return user else: logging.warning("Username not recognized.") return None
def edit_event(id): if not request.is_json: return gen_error_response("Request was not JSON.") try: data = request.get_json() except Exception as e: return gen_failure_response("Request was malformatted.") # Make sure creator matches authorized user. try: event = controller.get_event(id) if event is None: return gen_error_response(event_dne_text) user = User.get_user_in_token(request) if user is None: return gen_error_response("Invalid authorization.") if user.netid != event.creator: return gen_error_response( "Attempted to edit event for different user.") if controller.is_banned(user): return gen_error_response(banned_text) updated_event = controller.edit_event(id, data) except Exception as e: return gen_error_response(error_handler.main_handler(e)) if updated_event is None: return gen_error_response(event_dne_text) return gen_data_response(get_raw_event(updated_event))
def delete_event(id): try: event = controller.get_event(id) if event is None: return gen_error_response("No event with that id exists.") # Make sure it is the creator that is deleting the event. event_creator_netid = controller.get_event_creator(id) try: user = User.get_user_in_token(request) if user is None: return gen_error_response("Invalid authorization.") if user.netid != event_creator_netid: return gen_error_response( "Attempted to delete event for different user.") except AuthorizationError: return gen_error_response("Invalid authorization.") event = controller.delete_event(id) if event is None: return gen_error_response(event_dne_text) return gen_data_response(get_raw_event(event)) except Exception as e: return gen_error_response(error_handler.main_handler(e))
def remove_event_fav(userid, eventid): try: event = controller.get_event(eventid) user = controller.get_user_by_uid(userid) if event is None: return gen_error_response("No event with that id exists.") elif user is None: return gen_error_response("No user with that id exists.") # Make sure favoriter matches authorized user. try: token_user = User.get_user_in_token(request) if token_user is None or token_user.netid != user.netid: return gen_error_response( "Attempted to remove a favorite for different user.") except AuthorizationError: return gen_error_response("Invalid authorization.") if eventid in user.favorites: controller.remove_user_favorite(user, eventid) else: return gen_error_response( "You can't un-favorite an event that isn't in your favorites!") return gen_data_response(event.favorites) except Exception as e: return gen_error_response(error_handler.main_handler(e))
def get_user_in_token(request): user = None try: user = User.get_user_in_token(request) except AuthorizationError: pass return user
def add_event(): if not request.is_json: return gen_error_response("Request was not JSON.") try: data = request.get_json() if isinstance(data, str): # TODO: better error message return gen_failure_response("Request must be JSON, not string.") except: return gen_error_response("Request was malformatted.") try: # Check that the correct parameters have been given. missing_fields = get_missing_fields(data) if len(missing_fields) > 0: return gen_error_response("Request was missing %s parameter(s)." % ",".join(missing_fields)) # Make sure creator matches authorized user. user = User.get_user_in_token(request) if user is None: return gen_error_response("Invalid authorization.") if user.netid != data["creator"]: return gen_error_response( "Attempted to create event for different user.") if controller.is_banned(user): return gen_error_response(banned_text) # Try to add new event. new_event = controller.add_event(data) # Return id of newly added event. return gen_data_response({"id": str(new_event.id)}) except Exception as e: return gen_error_response(error_handler.main_handler(e))
def verify_password(username_or_token, password): print username_or_token user = User.verify_auth_token(username_or_token) if not user: user = User.query.filter_by(email=username_or_token).first() if not user or not user.verifypwd(password): return False g.user = user return True
def verify_token(token): # TODO: Make this less scary. if CONFIG["DEBUG"] and CONFIG["BYPASS_API_AUTH"]: return True user = User.verify_auth_token(token) if user is None: return False return True
def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(email = form.email.data, username = form.username.data, password = form.password.data) db.session.add(user) db.session.commit() flash("You have succesfully registered! You may now login") return redirect(url_for('mod_auth.login')) return render_template('mod_auth/register.html',form = form, title = "Register")
def facebook_authorized(): resp = facebook.authorized_response() if resp is None: # return 'Access denied: reason=%s error=%s' % ( # request.args['error_reason'], # request.args['error_description'] # ) return abort(401) if isinstance(resp, OAuthException): # return 'Access denied: %s' % resp.message return abort(401) access_token = resp['access_token'] session['facebook_token'] = (access_token, '') try: me = facebook.get('/me?fields=id') facebook_id = me.data['id'] token = api.get_token(facebook_id, access_token)['access_token'] res = api.get('/user/', token=token) user_id = res['user']['_id'] email = res['user']['email'] user = User(user_id) user.email = email login_user(user) session[str(user_id)] = user except client.OAuthException: return abort(401) # client_id = request.args.get('client_id') # scope = request.args.get('scope') # redirect_uri = request.args.get('redirect_uri') # response_type = request.args.get('response_type') return redirect(request.args.get('next'))
def patch_files(): res = {} try: id = request.args.get('id') current_id = str(session['user_id']) file = request.files['files[0]'] file_type = mime(file).split('/')[0] if file_type == 'image' and current_id == id: user = User.lookup_id(id) filename = secure_filename(file.filename) parts = filename.split('.') filename = '.'.join(parts[:-1]) + str(current_id) + '.' + parts[-1] destination = os.path.join(app.config['UPLOAD_FOLDER'], 'avatars/' + filename) file.save(destination) old_avatar = user.avatar user.avatar = filename user.update() try: if old_avatar != 'default.png': target = os.path.join(app.config['UPLOAD_FOLDER'], 'avatars/' + old_avatar) os.remove(target) except Exception: pass res = {'upload_success': True} elif current_id == id: res = {'upload_success': False, 'error': 'Invalid file type'} else: res = { 'upload_success': False, 'error': "You do not have permission to change this user's avatar" } except Exception: res = { 'upload_success': False, 'error': 'There was an error uploading your file' } return res, 200
def post(): form = request.json res = {} try: user = User(email=form.get('email'), username=form.get('username'), first_name=form.get('first_name'), last_name=form.get('last_name'), password=form.get('password'), instructor=form.get('instructor'), admin=False) user.save() global session session, res = gen_session(user, session) except Exception as e: try: res = {'error': 'Please choose a unique ' + get_field(e.orig)} except Exception: res = {'error': 'There was an error creating your account'} return jsonify(res), 200
def delete(): id = request.args.get('id') user = User.lookup_id(id) res = {} status = 200 if user and id == str(session['user_id']): try: user.delete() res = {'data': user} except Exception: res = {'error': 'Error deleting user'} status = 500 return jsonify(res), status
def oauth_callback(provider): if not current_user.is_anonymous(): return redirect(url_for('user.index')) oauth = OAuthSignIn.get_provider(provider) social_id, username, email = oauth.callback() if social_id is None: flash('Authentication failed.') return redirect(url_for('user.index')) user = User.query.filter_by(social_id=social_id).first() if not user: user = User(social_id=social_id, nickname=username, email=email) db.session.add(user) db.session.commit() login_user(user, True) return redirect(url_for('api_root'))
def login(): if not missing_session(): return go_user_home() form = LoginForm(request.form) if form.validate_on_submit(): user = User.find_by_email_or_username(form.emailOrUsername.data) if user and user.password == form.password.data: create_session(user) return redirect(url_for('user.profile', user_id=user.id)) flash('Wrong username or password', 'error') return render_template('user/login.html', form=form, session=session)
def patch(): user = User.lookup_id(request.args.get('id')) form = request.json res = {} if user: del form['avatar'] user = assign(form, user) try: user.update() res = {'data': user.as_dict()} except Exception: res = {'error': 'There was an error updating your account'} return jsonify(res), 200
def get(): try: id = int(request.args.get('id')) user = User.lookup_id(id) res = {} if user: user = user.as_dict() if session.get('user_id') != id: del user['email'] del user['password'] res = {'data': user} except Exception as e: res = {'error': 'There was an error finding this user'} return jsonify(res), 200
def save(self, warned): credentials = User.lookup_id(self.user_id) prerequisites = Course.lookup_id(self.course_id).prerequisites conflict = None if not warned: for prerequisite in prerequisites: matched = [ c for c in credentials if c.id == prerequisite.credential_id ] if matched.length == 0: conflict = prerequisite.id break if conflict: return "Missing prerequisite: " + Credential.lookup_id( conflict).name else: Base.save(self)
def auth(): form = request.json if form is None: form = {} res = {} try: identifier = form.get('identifier') password = form.get('password') user = User.lookup(identifier) if user and user.password == password: global session session, res = gen_session(user, session) else: res = {'error': 'Incorrect credentials'} except Exception as e: res = {'error': 'There was an error logging you in' + str(e)} out = jsonify(res) return out, 200
def get_favorites(userid): try: user = controller.get_user_by_uid(userid) if user is None: return gen_error_response("No user with that id exists.") # Make sure caller matches authorized user. try: token_user = User.get_user_in_token(request) if token_user is None or token_user.netid != user.netid: return gen_error_response( "Attempted to get a different user's favorites.") except AuthorizationError: return gen_error_response("Invalid authorization.") try: events = controller.get_favorite_events(user.favorites) events = [get_raw_event(event) for event in events] return gen_data_response(events) except Exception as e: return gen_error_response(error_handler.main_handler(e)) except Exception as e: return gen_error_response(error_handler.main_handler(e))
def report_event(eventid): try: if not request.is_json: return gen_error_response("Request was not JSON.") try: data = request.get_json() except Exception as e: return gen_error_response("JSON was malformatted.") if "reason" not in data: return gen_error_response("Request was missing field 'reason'.") try: user = User.get_user_in_token(request) report = controller.add_report(user, data["reason"], eventid) except RateError as e: return gen_error_response(str(e)) return gen_data_response(report) except ValidationError as e: return gen_error_response(str(e)) except Exception as e: return gen_error_response(error_handler.main_handler(e))
def add_event_fav(userid, eventid): try: event = controller.get_event(eventid) user = controller.get_user_by_uid(userid) if event is None: return gen_error_response("No event with that id exists.") elif user is None: return gen_error_response("No user with that id exists.") # Make sure favoriter matches authorized user. try: token_user = User.get_user_in_token(request) if token_user is None or token_user.netid != user.netid: return gen_error_response( "Attempted to add a favorite for different user.") except AuthorizationError: return gen_error_response("Invalid authorization.") if eventid not in user.favorites: controller.add_user_favorite(user, eventid) return gen_data_response( event.favorites) # need to return something or views gets angry except Exception as e: return gen_error_response(error_handler.main_handler(e))
def get_created_events(userid, include_past): try: user = controller.get_user_by_uid(userid) if user is None: return gen_error_response("No user with that id exists.") # Make sure creator matches authorized user. try: token_user = User.get_user_in_token(request) if token_user is None or token_user.netid != user.netid: return gen_error_response( "Attempted to get created events for different user.") except AuthorizationError: return gen_error_response("Invalid authorization.") if isinstance(include_past, str): # include_past defaults to True when an invalid value is passed. include_past = include_past != "False" events = controller.get_events_by_creator(str(user.netid), include_past) events = [get_raw_event(event) for event in events] return gen_data_response(events) except Exception as e: return gen_error_response(error_handler.main_handler(e))
def is_admin(id): user = User.lookup_id(id) return user.admin
def missing_session(): return not User.matches_id(id())