def process_message(self, data: dict): try: self.averager_job.toggle_job() self.averager_job.channels.append(data["channel"]) user_service = UserService() user = user_service.get_by_id(data["user"]) # get user's username(not DISPLAY NAME) if he doesn't exist in the db if not user: username = self.slack_client.api_call( method="users.info", user=data["user"])["user"]["name"] user = UserModel(username=username, user_id=data["user"]) numbers = self.parse_numbers(data["text"]) if numbers: for number in numbers: user.total_numbers += 1 user.sum_numbers = user.sum_numbers + number self.outputs.append([ data['channel'], f"from {user.username} {user.calculate_average()}" ]) user_service.post(user) except Exception as e: # Added this so exceptions could be seen in the terminal where the bot is running import traceback traceback.print_exc() print(str(e))
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data['username']): return {"message": "A user with that username already exists"}, 400 user = UserModel(data['username'], data['password']) user.save_to_db() return {"message": "User created successfully."}, 201
def signin(): form = LoginForm() if form.validate_on_submit(): user_name = form.username.data password = form.password.data user_model = UserModel(db.get_connection()) user_model.insert(user_name, password) return redirect('/login') return render_template('sign_in.html', title='Регестрация', form=form)
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data['username']) return {'message': 'usernamen alreaduy exist'}, 400 user = UserModel(**data) user.save_to_db() return{'message': 'A user was created successfully'},201
def login(): form = LoginForm() if form.validate_on_submit(): user_name = form.username.data password = form.password.data user_model = UserModel(db.get_connection()) exists = user_model.exists(user_name, password) if (exists[0]): session['username'] = user_name session['user_id'] = exists[1] return redirect("/index") return render_template('login.html', title='Авторизация', form=form)
def _post(self): username = self.request.get("username") email = self.request.get("email") model = UserModel(verified=False) model.assign(self) if model.validate(): if config.get_config("user_email_confirm") == "yes": model.put() user_confirm.send_confirmation_mail(username, email) values = { "message": _(u"""An email that contains the link to activate the account \ has been sent to the email"""), "redirect": None, } return self.render("noticepage", values) else: model.verified = True user_key = model.put() rbac.add_role(user_key, rbac.default_role("registered")) values = { "message": _(u"""Successfully registered."""), "redirect": None, } return self.render("noticepage", values) else: values = { "model": model } return self.render("admin_user_add", values)
def perform_installation(*args, **kwds): # Set up Role-based Access Control install_rbac() q = UserModel.query(UserModel.username == "admin").get() if not q: model = UserModel( username="******", display_name=_("Admin"), password="******", email="*****@*****.**", verified=True ) model.put(force_validation=False) rbac.add_role(model.key, rbac.default_role("super_admin")) # Configurations for item in config_setup.default_configs(): config.update_config(item.name, item.value, item.visible)
def add_claims_to_jwt(identity): user = UserModel.find_by_id(identity) #print("Permiss: ",identity) if user.permiss == "admin": return {'is_admin': True} else: return {'is_admin': False}
def post(self, ids): """Posts a listing to the database. Args: ids (str): The listing id of the listing being posted. Returns: message: What happened with the post call. """ # what the user will send to the post request (in good format) data = Listing.parser.parse_args() # In our case, the user sends the price as JSON, but the item name gets passed into the function # if user doesn't exist if not UserModel.find_by_google_tok(data['google_tok']): return {"message": "invalid google token, user does not exist in database"} if not BookModel.find_by_isbn(ids): # if book doesn't exist return {"message": "invalid isbn, book model does not exist in database"} isbn = int(ids) item = ListingModel(data["price"], data["condition"], isbn, data["google_tok"], data["status"]) try: item.save_to_db() except: # internal server error return{"message": "An error occurred while inserting"}, 500 return {"message": "post was successful"}, 201 # post was successful
def identity(payload): ''' identity method for JWT returns user_id from DB ''' user_id = payload['identity'] return UserModel.find_by_id(user_id)
def authenticate(username, password): ''' authenicate method for JWT returns user if user exists in DB ''' user = UserModel.find_by_username(username) if user and safe_str_cmp(user.password, password): return user
def perform_installation(*args, **kwds): #Set up Role-based Access Control install_rbac(); q = UserModel.query(UserModel.username=="admin").get() if not q: model = UserModel(username="******", password="******", email="*****@*****.**", verified=True) model.put(force_validation=False) rbac.add_role(model.key, rbac.default_role("super_admin")) #Configurations conf = [ ("site_name", "Name", True), ("session_secret_key", utils.generate_random_string(30), False), ("admin_email", "*****@*****.**", True), ("user_email_confirm", "no", True), ] for item in conf: config.update_config(item[0], item[1], item[2])
def post(self): data = parser.parse_args() current_user = UserModel.find_by_username(data['username']) if not current_user: return { 'message': 'User {} doesn\'t exist'.format(data['username']) } if UserModel.verify_hash(data['password'], current_user['password']): access_token = create_access_token( identity=current_user.doc_id, expires_delta=datetime.timedelta(hours=1)) return { 'message': 'Logged in as {}'.format(current_user["username"]), 'access_token': access_token, } else: return {'message': 'Wrong credentials'}
def post(self, type): current_userId = get_jwt_identity() if (UserModel.remove_poke_type_in_user(current_userId, type) != None): return { 'status': "successful", "message": "Le type a bien été supprimé" } return { 'status': "error", "message": "Le type voulant être supprimé n'est pas présent" }
def update(self, form_data): """Updates a category and returns a json object""" try: user = UserModel(form_data['user_token']) form_data['created_by'] = user.email category = CategoryModel(form_data).update(self.db_session) except exc.IntegrityError as e: self.db_session.rollback() category = CategoryModel({'errors': 'Error Updating Category'}) finally: self.db_session.close() return jsonify(category.attributes())
def post(self): jti = get_jwt() BLACKLIST.add(jti['jti']) user = UserModel.find_by_id(jti['sub']) user.status = "invisible" user.lastConnect = datetime.now().strftime('%Y-%m-%d %H:%M:%S') user.update_to_db() #print(user.json()) return { 'status': 'success', 'message': 'Successfully logged out.' }, 200
def post (self): data=UserRegister.parser.parse_args() #get data from the parser if UserModel.find_by_usernsme(data['username']): #help to avoid dublicate users, check if user=None than..put before connection, or it never close return {"message":"A user with that username already exists"},400 connection = sqlite3.connect('data.db') cursor = connection.cursor() query = "INSERT INTO users VALUES (NULL, ?, ?)" #NUL: because id is auto incrementing cursor.execute(query, (data['username'], data['password'])) connection.commit() connection.close() return {"message": "User was created sucessfully"}, 201
def update(self, form_data): """Updates an item and returns a json object with the item values""" try: """form includes user_token, which is used to get user email""" user = UserModel(form_data['user_token']) form_data['created_by'] = user.email item = ItemModel(form_data).update(self.db_session) except exc.IntegrityError as e: self.db_session.rollback() item = ItemModel({'errors': 'Error Updating Item'}) finally: self.db_session.close() return jsonify(item.attributes())
def create(self, form_data): """Creates a new category and returns a json object""" try: """form includes user_token, which is used to get user email""" user = UserModel(form_data['user_token']) form_data['created_by'] = user.email category = CategoryModel(form_data).create(self.db_session) except exc.IntegrityError as e: self.db_session.rollback() category = CategoryModel({'errors': 'failed to update database'}) finally: self.db_session.close() return jsonify(category.attributes())
def delete(self, name, form_data): """Deletes a category and returns a json object""" try: """form includes user_token, which is used to get user email""" user = UserModel(form_data['user_token']) category = CategoryModel( {'name': name, 'created_by': user.email} ).delete(self.db_session) except exc.IntegrityError as e: self.db_session.rollback() category = CategoryModel({'errors': 'Error Deleting Category'}) finally: self.db_session.close() return jsonify(category.attributes())
def post(self): data = UserRegister.parser.parse_args() regex = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$' if UserModel.find_by_user(data['username'], 'username'): return { 'status': 'failed', "message": "A user with that username already exists" }, 400 elif not re.search(regex, data['email']): return {'status': 'failed', "message": "Invalid Email"}, 400 elif data['password'] != data['passwordConfirm']: return {'status': 'failed', "message": " Password not match"}, 400 hashed = generate_password_hash(data['password'], method='sha256') time = datetime.now() user = UserModel( data['username'], data['email'], hashed, _id=UserModel.current_user() + 1, status="online", lastConnect=time.strftime('%Y-%m-%d %H:%M:%S'), picture= "https://firebasestorage.googleapis.com/v0/b/projectdoc-5af7b.appspot.com/o/template%2FArtboard%201.png?alt=media&token=b74d1752-21ae-4255-8d37-1440d1c967d5" ) print(user.json()) user.save_to_db() access_token = create_access_token(identity=user.userId, fresh=True, expires_delta=timedelta(hours=3)) refresh_token = create_refresh_token(user.userId) return make_response( { 'status': 'success', "data": { "userId": user.userId, "username": user.username, "permiss": user.permiss, "status": user.status, "picture": user.picture, "expires_token": time + timedelta(hours=3), "access_token": access_token, "refresh_token": refresh_token } }, 200)
def post(self, type): current_userId = get_jwt_identity() req = Request('https://pokeapi.co/api/v2/type/' + type + '/', headers={'User-Agent': 'Mozilla/5.0'}) try: resp = urlopen(req) except urllib.error.HTTPError as e: if e.code == 404: return {'error': "Le type voulant être ajouté n'existe pas"} if (UserModel.add_poke_type_in_user(current_userId, type) != None): return { 'status': "successful", "message": "Le type a bien été ajouté" } return { 'status': "error", "message": "Le type voulant être ajouté est déja present" }
def post(self): data = ForgetPassword.parser.parse_args() regex = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$' if re.search(regex, data['email']): user = UserModel.find_by_user(data['email'], 'email') else: return {"status": "failed", "message": "Invalid Email"}, 400 if user: token = create_access_token(identity=user.userId, fresh=True, expires_delta=timedelta(hours=4)) endpoint = f'http://localhost:80/lisa/user/resetPassword/?token={token}' SendEmail.send_reset_email(user, endpoint) return {'status': 'success', 'data': {'access_token': token}}, 200 else: return { "status": "failed", "message": "There is no account with this email. You must register first." }, 400
def put(self, token): claim = get_jwt() #print(claim) user = UserModel.find_by_id(claim['sub']) #print(user.json()) data = ResetPassword.parser.parse_args() if data['password'] != data['passwordConfirm']: return {'status': 'failed', "message": " Password not match"}, 400 hashed = generate_password_hash(data['password'], method='sha256') setattr(user, 'password', hashed) user.update_to_db() access_token = create_access_token(identity=user.userId, fresh=True, expires_delta=timedelta(hours=3)) refresh_token = create_refresh_token(user.userId) return { "status": "success", "data": { "access_token": access_token, "refresh_token": refresh_token } }, 200
def get(self): username = self.request.get("user") token = self.request.get("token") q = ndb.gql("SELECT token FROM UserConfirmationModel WHERE username = :1", username).get() if (not q) or (q.token != token): values = { "message": _("Your confirmation link is invalid, sorry but please check your mail box again."), "redirect": None, } return self.render("noticepage", values) else: q.delete() the_user = UserModel.query(UserModel.username == username).get() the_user.verified = True user_key = the_user.put() rbac.add_role(user_key, rbac.default_role("registered")) values = { "message": _( "Congratulations! Your account has been successfully activated \ , thanks for registering." ), "redirect": self.uri_for("home"), } return self.render("noticepage", values)
def update_q_history(qid): temp = UserModel.get_all() for element in temp: AnswerModel.add_q_stats(element.userid, qid)
def username(self): user = UserModel.by_user_id(self.userID) if user is None: return self.userID return user.username
def get(self): current_userId = get_jwt_identity() data = UserModel.return_user_infos(current_userId) return {'status': "successful", 'data': data}
from sqlalchemy import create_engine engine = create_engine('sqlite:///user.db', echo = True) from user import UserModel, EndPointRpi #from datetime import datetime, time #from sqlalchemy import Column, Integer, String #from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind = engine) session = Session() # a = datetime.now() c1 = UserModel(username = '******', password = '******') session.add(c1) session.commit()
def post(self): data = UserLogin.parser.parse_args() if not data['username/email']: return { 'status': 'failed', "message": "Please Enter username/email" }, 400 elif not data['password']: return { 'status': 'failed', "message": "Please Enter password" }, 400 regex = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$' if re.search(regex, data['username/email']): type = 'email' else: type = 'username' user = UserModel.find_by_user(data['username/email'], type) if user: if check_password_hash(user.password, data['password']): if user.status == "suspended": if user.lastConnect: if datetime.now() <= user.lastConnect: diff = timedelta( seconds=(user.lastConnect - datetime.now()).total_seconds()) t = str(diff).split(':') return { "status": "failed", "message": "Your account is suspended, remain time {} Hours {} Minutes {} Seconds" .format(t[0], t[1], int(float(t[2]))) }, 403 else: return { "status": "failed", "message": "Your account is suspended, please contact admin." }, 403 time = datetime.now() access_token = create_access_token( identity=user.userId, fresh=True, expires_delta=timedelta(hours=3)) refresh_token = create_refresh_token(user.userId) user.status = "online" user.lastConnect = time.strftime('%Y-%m-%d %H:%M:%S') #print(user.json()) user.update_to_db() return make_response( { 'status': 'success', "data": { "userId": user.userId, "username": user.username, "permission": user.permiss, "status": user.status, "picture": user.picture, "expires_token": time + timedelta(hours=3), "access_token": access_token, "refresh_token": refresh_token } }, 200) return {'status': 'failed', "message": "Password incorrect"}, 400 else: return {'status': 'failed', "message": "User does not exist"}, 400
from db import DB from user import UserModel from drug import DrugModel from basket import BasketModel db = DB() users_model = UserModel(db.get_connection()) users_model.init_table() users_model.insert("admin", "admin") news_model = DrugModel(db.get_connection()) news_model.init_table() basket_model = BasketModel(db.get_connection()) basket_model.init_table()