def register():
    if current_user.is_authenticated:
        return flask.redirect(flask.url_for("feedback.feedback"))

    form = RegisterForm()

    if form.validate_on_submit():
        hashed_password = UserModel.hash_password(form.password.data)
        user = UserModel(name=form.name.data,
                         email=form.email.data.lower(),
                         password=hashed_password)

        if UserModel.verify_email(form.email.data):
            flask.flash("An account with this email already exists", "danger")
        else:
            try:
                app.db.session.add(user)
                app.db.session.commit()
                flask.flash(
                    f"The account for {form.email.data} has been created",
                    "success")
                return flask.redirect(flask.url_for("user.login"))
            except Exception as e:  # pragma: no cover
                print(e)
    return flask.render_template("user/register.html", form=form)
Beispiel #2
0
    def _show_contact(self):
        user_cache = read_token()
        current_user = UserModel(user_cache.u_name)
        contact_name = list()
        if current_user.user_is_valide() :
            global contact_list
            contact_list = current_user.get_contact_list()
            i = 1
            #print(contact_list)
            for contact in contact_list:
                self.Scrolledlistbox1.insert( i , f"{i}.{contact[1]} {contact[2]}")
                conctact = list(contact)
                #print('lsit conctact :', contact)
                i += 1
                if contact[2] :

                    name_slug =  '_'.join(contact[2].split(' '))
                    
                else:
                    name_slug = contact[2]

               
                name_slug2 = '_'.join(contact[1].replace("+", ' ').split(' '))

                slug = str(f'{conctact[0]}_{name_slug2}')
                slug.replace("(", "_").replace(")", "_").replace("'", "_").replace("-", "_")
                print('new slug: ', slug)
                #contact_name.append(slug)
                contact_name.append(str(f'{contact[1]}_{name_slug}'))
            #print(contact_name)

            global contact_dic
            contact_dic = {name:value for name, value in zip(contact_name,contact_list)}
    def post(self):
        json_data = request.get_json()
        
        if not json_data:
            return {'message': 'No input data provided'}

        user_data = user_schema.load(json_data)

        if not UserModel.find_by_username(username=user_data['username']):
            return {'message': 'Username is not exists'}

        user_ = user_schema.dump(UserModel.find_by_username(username=user_data['username']))
        
        if Utils.decrypt_pass(user_data['password'], user_['password']):
            access_token = create_access_token(user_['username'])
            refresh_token = create_refresh_token(user_['username'])

            return {
                'message': "Login successful!",
                'access_token': access_token,
                'refresh_token': refresh_token
            }
        else:
            return {
                'message': 'Username or password wrong!'
            }
Beispiel #4
0
    def post(self):
        """
        Register a new user
        ---
        tags:
            - User API
        parameters:
            - name: username
              in: body
              type: string
              required: true
              description: the username
            - name: password
              in: body
              type: string
              required: true
              description: the password
            - name: email
              in: body
              type: string
              required: true
              description: the email adress
            - name: phonenumber
              in: body
              type: string
              required: true
              description: the phonenumber of the new user 
        responses:
            200:
                description: user sucessfully registered
                schema:
                    id: RegisterResponse
                    properties:
                        message:
                            type: string
                            description: user successful created
            400:
                description: the user already exists or not all required data provided
                schema:
                    id: RegisterResponse
                    properties:
                        message:
                            type: string
                            description: user exists or not all data provided
        """
        data = _user_parser.parse_args()

        if UserModel.find_user_by_username(data["username"]):
            return {"message": "User exists!"}, 400
        if not data["username"] or not data["password"] or not data[
                "email"] or not data["phonenumber"]:
            return {"message": "Not all required data provided!"}, 400
        user = UserModel(data["username"], data["password"], data["email"],
                         data["phonenumber"])
        user.save_to_db()
        return {"message": "User {} created!".format(data["username"])}
Beispiel #5
0
    def get(self, userid=None):
        if userid:
            data = user_schema.dump(UserModel.find_by_id(userid))
            if not data:
                return {'message': 'User not found!'}

            return {'status': 'success', 'user_data': data}
        else:
            data = UserModel.find_all()
            return {'data': data}
Beispiel #6
0
    def test_logout(self):
        u = UserModel(name="Test User",
                      email="*****@*****.**",
                      password="******")
        db.session.add(u)
        db.session.commit()

        with client.session_transaction() as sess:
            sess["user_id"] = int(u.get_id())
            sess["_fresh"] = True

        response = client.get("/logout", follow_redirects=True)
        self.assertTrue(b"Farm Fresh Produce", response.data)
 def post(self):
     data = parser.parse_args()
     new_user = UserModel(
         username=data['username'],
         password=data['password'],
         name=data['name'],
         email=data['email']
     )
     try:
         new_user.save_to_db()
         return {
             'message': 'User {} was created'.format(data['username'])
         }
     except None:
Beispiel #8
0
    def post(self):
        json_data = request.get_json()
        if not json_data:
            return {'message': 'No data input provided'}

        if user_schema.dump(UserModel.find_by_username(json_data['username'])):
            return {'message': 'Username is already exists'}

        user = UserModel(username=json_data['username'],
                         password=Utils.encrypt_pass(json_data['password']))

        user.add()
        res = user_schema.dump(user)

        return {'result': res}
Beispiel #9
0
    def delete(self):
        """
        Delete a user
        ---
        tags:
            - User API
        parameters:
            - name: JWT Token
              in: header
              type: string
              required: true
              description: The JWT Token with format "Authorization Bearer <JWT Token>"
        responses:
            200:
                description: user sucessfully deleted
                schema:
                    id: user_delete_response
                    properties:
                        message:
                            type: string
                            description: User deleted!
            404:
                description: Error user not found.
        """
        user = UserModel.find_user_by_id(get_jwt_identity())
        if user:
            user.remove_from_db()
            return {"message": "User deleted!"}, 200

        return {"message": "User not found!"}, 404
Beispiel #10
0
    def post(self):
        """
        Change the user password
        ---
        tags:
            - User API
        parameters:
            - name: JWT Token
              in: header
              type: string
              required: true
              description: The JWT Token with format "Authorization Bearer <JWT Token>"
            - name: newpw
              in: body
              type: string
              required: true
              description: the new password for the user
        responses:
            200:
                description: Password successfully changed.
            500:
                description: Error user not found.
        """
        user = UserModel.find_user_by_id(get_jwt_identity())
        data = request.get_json()
        print(data)
        if not data['newpw']:
            return {"message": "No password provided"}, 500

        if user:
            user.password = data['newpw']
            user.save_to_db()
            return {"message": "Password successfully changed"}, 200
Beispiel #11
0
class UserController:
    user = UserModel()

    @classmethod
    @validate_password
    def create(cls, username, password):
        return cls.user.insert(username, password)

    @classmethod
    def get(cls, username, password):
        return cls.user.get_id(username, password)

    @classmethod
    def is_user(cls, username, password):
        print("USER:"******"LOGGED:", cls.user.is_logged(username, password))
        return cls.user.is_logged(username, password)

    @classmethod
    def logged(cls, username, password):
        cls.user.logged(username, password)

    @classmethod
    def logged_out(cls, username, password):
        cls.user.logged_out(username, password)
Beispiel #12
0
    def test_submit_feedback(self):
        u = UserModel(name="Test User",
                      email="*****@*****.**",
                      password="******")
        db.session.add(u)
        db.session.commit()

        with client.session_transaction() as sess:
            sess["user_id"] = int(u.get_id())
            sess["_fresh"] = True

        response = client.get("/feedback")
        self.assertTrue(b"Test User, your feedback is appreciated!",
                        response.data)
        feedback = self.feedback(5, True, True, False, False, "Test Comment",
                                 1)
        self.assertTrue(b"Thanks for your feedback, Test User.", response.data)
Beispiel #13
0
def add_user():
    form = UserForm()
    if request.method == 'POST':
        data = {'name': request.form['name'], 'email': request.form['email']}
        user = UserModel(**data)
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('book.add_book'))
    return render_template('add_user.html', form=form)
Beispiel #14
0
    def test_provide_multiple_feedback_in_one_session(self):
        u = UserModel(name="Test User",
                      email="*****@*****.**",
                      password="******")
        db.session.add(u)
        db.session.commit()

        with client.session_transaction() as sess:
            sess["user_id"] = int(u.get_id())
            sess["_fresh"] = True

        client.get("/feedback")
        self.feedback(5, True, True, False, False, "Test Comment", 1)
        client.get("/")
        response = client.get("/feedback")
        self.assertTrue(
            b"Thanks, Test User! We have recorded your recent feedback.",
            response.data)
Beispiel #15
0
    def __save_edit(self):
        status , contact_to_edit = self.__validate_change()
        nom = contact_to_edit.c_nom
        prenoms= contact_to_edit.c_prenoms
        numero = contact_to_edit.c_numero
        user_id = contact_to_edit.c_user_id
        contact_id = contact_to_edit.c_id

        CurrentUser = UserModel(session_data.session_username)

        updateContact = ContactModel(nom=nom, prenoms=prenoms, numero=numero , user_id=user_id ,\
         contact_id=contact_id )

        assert list(CurrentUser.get_id)[0] > 0 , ''' Attentions vous êtes pas connecté '''
        updateContact.set_id(CurrentUser.get_id[0])
        
        if status == 1:
            #print('il y a modification avec photo')
            extention ='png'
            image_path = contact_to_edit.c_photo
            destination = f'{config.IMAGES_DIR}/img_{contact_to_edit.c_id}.{extention}'

            new_photo = ImageEdit(image_path, (150,  200) , destination)
            succes = new_photo.save()
            if succes:
                updateContact.update_img()
                #print('photo edité')
            else:
                #print('photo non edité')
                pass

            if updateContact.update_valide() :
                update = updateContact.update()
                if update :
                    show_info('info', 'Information enregistré !')
                else:
                    show_error('error', 'problème lors de l\' enregistrement !')
            else:
                show_warming("error",'Le nom et Prénoms existes déja !')

        elif status == 0:
            #print('modification sans photo')

            if updateContact.update_valide() :
                update = updateContact.update()
                if update :
                    show_info('info', 'Information enregistré !')
                else:
                    show_error('error', 'Le nom et Prénoms existes déja !')
                #updateContact.update()
            else:
                show_warming("error",'Le nom et Prénoms existes déja !')

        else:
            show_info('attentions','veuillez selectionner un contact à modifier !')
Beispiel #16
0
 def setUp(self):
     self.app_context = app.app_context()
     self.app_context.push()
     db.create_all()
     data = {'author': 'Kapa', 'name': 'Stop', 'edition': 'Sunshine',
             'year': 2017, 'user': '******', 'translator': 'Stefano'}
     book = BookModel(**data)
     db.session.add(book)
     data1 = {'name': 'Tony', 'email': '*****@*****.**'}
     user = UserModel(**data1)
     db.session.add(user)
     db.session.commit()
Beispiel #17
0
    def setUp(self) -> None:
        ctx = app.app_context()
        ctx.push()
        with client:
            password_hash = pbkdf2_sha256.hash("password")
            test_user = UserModel(name="John Doe",
                                  email="*****@*****.**",
                                  password=password_hash)

            db.session.add(test_user)
            # db.session.add(test_feedback)
            db.create_all()
            db.session.commit()
Beispiel #18
0
    def login(email, password):
        """
        logs in an existing user to the application
        and returns an API response with status
        code set to 201 on success
        
        :param email: 
        :param password:  
        """
        if not email or not password:
            response = jsonify({'Error': 'Missing login credentials'})
            response.status_code = 400
            return response

        if not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)",
                        email):
            response = jsonify({
                'message':
                'Invalid email! A valid email should in this format [email protected] or [email protected]'
            })
            response.status_code = 401
            return response

        user = UserModel(email=email, password=password)
        user_data = user.query.filter_by(email=email).first()

        # If Login successful
        if user_data and user.check_password(user_data.password, password):
            response = jsonify({
                'Status': user.email + ' Login Successful',
                'token': user_data.id
            })
            response.status_code = 201
            return response

        response = jsonify({'Error': 'Incorrect email or password'})
        response.status_code = 401
        return response
Beispiel #19
0
    def post(self):
        """
        Login as a user
        ---
        tags:
            - User API
        parameters:
            - name: username
              in: body
              type: string
              required: true
              description: the username
            - name: password
              in: body
              type: string
              required: true
              description: the password 
        responses:
            200:
                description: user sucessfully logged in
                schema:
                    id: TokenRefresh
                    properties:
                        accessToken:
                            type: string
                            description: new token for the current user
                        id:
                            type: string
                            description: id of the logged in user
            401:
                description: the credentials are invalid
                schema:
                    id: LoginResponse
                    properties:
                        message:
                            type: string
                            description: Invalid credentials
        """
        data = _user_parser.parse_args()

        user = UserModel.find_user_by_username(data["username"])

        if user and user.password == data["password"]:
            access_token = create_access_token(
                identity=user.id,
                fresh=True)  # Puts User ID as Identity in JWT

            return {"accessToken": access_token, "id": str(user.id)}, 200

        return {"message": "Invalid credentials!"}, 401
Beispiel #20
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for("feedback.feedback"))
    form = LoginForm()

    if form.validate_on_submit():
        user = UserModel.query.filter_by(email=form.email.data.lower()).first()
        if user and UserModel.verify_password(form.password.data,
                                              user.password):
            login_user(user, remember=form.remember.data)
            next_page = request.args.get("next")
            if next_page:
                return redirect(next_page)
            return redirect(url_for("feedback.feedback"))
        else:
            flash(f"Please check your credentials", "danger")
    return render_template("user/login.html", form=form)
Beispiel #21
0
    def get(self):
        """
        Get user infos
        ---
        tags:
            - User API
        parameters:
            - name: JWT Token
              in: header
              type: string
              required: true
              description: The JWT Token with format "Authorization Bearer <JWT Token>"
        responses:
            200:
                description: Returns all profile infos about the user
                schema:
                    id: user_respone
                    properties:
                        id:
                            type: string
                            description: The id of the user
                        username:
                            type: string
                            description: The username of the user
                        email:
                            type: string
                            description: The email of the user
                        phonenumber:
                            type: string
                            description: The given phonenumber
            404:
                description: Error user not found.
        """
        user = UserModel.find_user_by_id(get_jwt_identity())
        if user:
            return user.json()

        return {"message": "User not found!"}, 404
Beispiel #22
0
 def __init__(self):
     self.object = UserModel()
Beispiel #23
0
    def register(email, password, name):
        """
        Registers a new user to the application
        and returns an API response with status
        code set to 201 on success
        
        :param email: 
        :param password: 
        :param name:  
        """
        if not name or not email or not password:
            response = jsonify({'Error': 'Missing Values'})
            response.status_code = 404
            return response

        if type(name) is int:
            response = jsonify({'Error': 'Numbers cant be a Name'})
            response.status_code = 400
            return response

        if not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)",
                        email):
            response = jsonify({
                'message':
                'Invalid email! A valid email should in this format [email protected] or [email protected]'
            })
            response.status_code = 401
            return response

        if re.match(r"(^[ ]*$)", name):
            response = jsonify({'message': 'A space is not a name'})
            response.status_code = 401
            return response

        # if re.match(r"(^[ a-zA-Z_]*$)", name):
        #     response = jsonify(
        #     {'message':
        #     'Name dont start with spaces' }
        #     )
        #     response.status_code = 401
        #     return response

        if not re.match(r"(^[a-zA-Z_ ]*$)", name):
            response = jsonify({'message': 'Name should be in alphabetical'})
            response.status_code = 401
            return response

        if len(password) < 6:
            response = jsonify({'Error': 'Password is short'})
            response.status_code = 400
            return response

        # if not name.isalpha():
        #     response = jsonify({'Error': 'Names must be in alphabetical strings'})
        #     response.status_code = 400
        #     return response

        user = UserModel(email=email, password=password, name=name)

        if user.query.filter_by(email=email).first():
            response = jsonify({'Error': 'Email Already exists'})
            response.status_code = 401
            return response

        user.save()
        response = jsonify({
            'Status': user.email + ' Successfully registered',
            'token': user.id
        })
        response.status_code = 201
        return response
Beispiel #24
0
    def post(self):
        """
        Create a new entry
        ---
        tags:
            - Entry API
        parameters:
            - name: JWT Token
              in: header
              type: string
              required: true
              description: The JWT Token with format "Authorization Bearer <JWT Token>"
            - name: title
              in: body
              type: string
              required: true
              description: the title of the entry
            - name: text
              in: body
              type: string
              required: true
              description: the text of the entry
            - name: tags
              in: body
              type: array
              required: true
              description: the tags for a entry
        responses:
            200:
                description: returns the new entry
                schema:
                    id: user_respone
                    properties:
                        id:
                            type: string
                            description: The id of an entry
                        title:
                            type: string
                            description: The title of the entry
                        text:
                            type: string
                            description: the text for an entry
                        author:
                            type: string
                            description: The username of the author
                        author_id:
                            type: string
                            description: The id of the author
                        date:
                            type: string
                            description: the creation date for an entry
                        tags:
                            type: array
                            description: the tags for an entry
        """
        conn = sqlite3.connect('data.db')
        c = conn.cursor()

        data = _entry_parser.parse_args()

        entry = EntryModel(data["title"], data["text"], UserModel.find_user_by_id(get_jwt_identity()).json()[0]['username'], get_jwt_identity())
        entry.save_to_db()
        tags_to_db = ""

        counter = 0
        for i in data['tags']:
            counter += 1
            tags_to_db += str(i) 
            if counter == len(data['tags']):
                pass
            else:
                tags_to_db += ";"
        c.execute("UPDATE entries SET tags = '" + tags_to_db +"' WHERE ID=" + str(entry.json()['id']))
        conn.commit()
        conn.close()
        ret_json = EntryModel.find_entry_by_id(entry.json()['id']).json()
        ret_json["tags"] = data['tags']
        return ret_json
Beispiel #25
0
    def put(self):
        """
        Change an entry
        ---
        tags:
            - Entry API
        parameters:
            - name: JWT Token
              in: header
              type: string
              required: true
              description: The JWT Token with format "Authorization Bearer <JWT Token>"
            - name: id
              in: body
              type: string
              required: true
              description: the id of the entry that you want to change
            - name: title
              in: body
              type: string
              required: true
              description: the title of the entry
            - name: text
              in: body
              type: string
              required: true
              description: the text of the entry
            - name: tags
              in: body
              type: array
              required: true
              description: the tags for a entry
        responses:
            200:
                description: Entry changed!
            404:
                description: Entry not found!
            403:
                description: You are not allowed to change the entry! Only the Author can change it
        """
        data = _entry_parser.parse_args()

        entry = EntryModel.find_entry_by_id(data["id"])

        if entry:
            if UserModel.find_user_by_id(get_jwt_identity()) is not UserModel.find_user_by_username(entry.json()["author"]):
                return {
                        "message": "You are not allowed to change the entry!"
                    }, 403
            else:
                tags_to_db = ""
                counter = 0
                for i in data['tags']:
                    counter += 1
                    tags_to_db += str(i) 
                    if counter == len(data['tags']):
                        pass
                    else:
                        tags_to_db += ";"
                data["tags"] = tags_to_db
                entry.title = data["title"]
                entry.text = data["text"]
                entry.date = str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                entry.tags = tags_to_db
                entry.save_to_db()
                
                return {
                        "message": "Entry changed!"
                    }, 200
        return {
                   "message": "Entry not found!"
               }, 404
Beispiel #26
0
    def _add_contact(self):
        c_name_value = self.name_entry.get()
        c_last_name_value = self.prenoms_entry.get()
        c_number_value = self.numero_entry.get()
        c_photo = PopMenu.default_img
        user_id = 0

        if len(c_name_value) >= 2 and len(c_number_value) >= 3:

            NewContact = ContactModel(nom =c_name_value, prenoms = c_last_name_value, \
                numero=c_number_value, photo= c_photo, user_id=user_id)

            if PopMenu.load_photo != None:
                last_id = NewContact.get_last_id
                NewContact.set_photo(f'img_{last_id + 1}')

            session_id_name = login_gui.session_username

            if session_id_name != 'BotUser':
                user_session = UserModel(session_id_name)

                assert user_session.get_id[
                    0] > 0, """ Attention vous êtes pas connecté"""

                NewContact.set_id(user_session.get_id[0])

                validate = NewContact.contact_validator()

                if validate.get('name') or validate.get('number'):

                    if validate.get('name'):
                        show_info('error', 'Le nom entré exite déja :')
                    else:
                        show_info('error', 'Le numero entré exite déja :')

                else:

                    if NewContact.get_user_id > 0:

                        contact_saved = NewContact.save()

                        if contact_saved:
                            if PopMenu.load_photo != None:

                                photo_name = NewContact.get_photo
                                extention = PopMenu.default_img_extention

                                if self.__save_user_photo(
                                        photo_name, extention):
                                    show_info(
                                        'Info',
                                        'Le contact a bien été ajouté et enregistré avec photo'
                                    )
                                else:
                                    print('info',
                                          'impossible d\'ajouter la photo')
                            else:
                                show_info(
                                    'info',
                                    'contact ajouter mais photo no spécifiée ')
                        else:
                            show_warming('info',
                                         'le contact n\'a pas pu être ajouté')
            else:
                show_warming(
                    'Attentions',
                    'Vous devez être "connecté"  avant d\'avnant d\'ajouter un contact'
                )
        else:
            show_info('error', 'veuillez fournit au moin un nom et numero ')
Beispiel #27
0
  def post(self):
    """
    Post request for registering a new user.
    This requires a JSON data with required user fields
    {
        "username": "******",
        "password": "******",
        "firstName": first_name,
        "lastName": "last_name",
        "email": "*****@*****.**"
    }
    Required headers include
      Content-Type:   application/json
      Accept:         application/json
    :return: JSON Payload
    if we succeed to add a user entry in database, the returned response_object will look like following:
      response_object = {
        "status": "success", # not present if the request fails
        "message": "Successfully registered."/"failure message",
      }
    To get the auth token user has to perform the login action
    """
    # get the post data
    user_data = request.get_json()
    if not user_data:
      print("Invalid json object: {}", request.url)
      abort(400, message="Invalid json object in request")

    username = user_data.get("username")
    if not username:
      print("Missing username field")
      abort(
          400, message="Missing username field",
      )
    username = username.lower()
    if username == "admin":
      print("User tried to register with admin username")
      abort(
          400, message="Please choose another username",
      )

    password = user_data.get("password")
    if not password:
      print("Missing password field")
      abort(
          400, message="Missing password field",
      )

    emailID = user_data.get("email")
    if not emailID:
      print("Missing email field")
      abort(
          400, message="Missing email field",
      )

    firstName = user_data.get("firstName")
    if not firstName:
      print("Missing firstName field")
      abort(
          400, message="Missing firstName field",
      )

    lastName = user_data.get("lastName")
    if not lastName:
      print("Missing lastName field")
      abort(
          400, message="Missing lastName field",
      )

    # validate the email field
    try:
      valid = validate_email(emailID)
      email = valid.email
    except EmailNotValidError:
      print("Invalid email {}", emailID)
      abort(400, message=f"Invalid email: {emailID}")

    # check if user already exist
    user = UserModel.query.filter_by(username=user_data.get("username")).first()
    if user:
      print(
          "A user tried to re-register. Username: {}", user.username
      )
      abort(403, message="A user with that name already exists.")

    try:
      user = UserModel(
          bcrypt_log_rounds=None,
          username=username,
          password=password,
          firstName=firstName,
          lastName=lastName,
          email=email,
      )

      # insert the user
      Database.db_session.add(user)
      Database.db_session.commit()
      print(
          "New user registered, username: {}, email: {}", username, email
      )

      response_object = {
          "status": "success",
          "message": "Successfully registered.",
      }
      response = jsonify(response_object)
      response.status_code = 201
      return make_response(response, 201)
    except Exception:
      print("Exception while registering a user")
      Database.db_session.rollback()
      abort(500, message="INTERNAL ERROR")
Beispiel #28
0
 def get(self):
     uuid = self.request.get('uuid')
     user_entity = UserModel(id=uuid, cafe_stamps={})
     user_entity.put()