Beispiel #1
0
def register():
    json_data = request.json

    try:
        user_data = RegisterSchema().load(json_data)
    except ValidationError as error:
        return {'errors': error.messages}, HTTPStatus.BAD_REQUEST

    try:
        user = User.create(username=user_data['username'],
                           password=user_data['password'],
                           first_name=user_data['first_name'],
                           last_name=user_data['last_name'])  # NOQA
    except Exception:  # FIXME
        return {}, HTTPStatus.UNPROCESSABLE_ENTITY

    token = generate_confirmation_token(user_data['username'])
    confirm_url = f'{API["confirm_url"]}{token}'
    html = render_template('user/activate.html',
                           confirm_url=confirm_url)  # NOQA
    subject = 'Please confirm your email'  # NOQA
    # email_manager.send_email(user.username, subject, html)
    user.is_active = True
    user.save()

    return {}, HTTPStatus.OK
Beispiel #2
0
    def post(self):
        registerData = {
            'username': request.json['username'],
            'password': request.json['password'],
            'email': request.json['email']}
        user = User.query.filter_by(username=registerData['username']).first()
        userEmail = User.query.filter_by(email=registerData['email']).first()

        if user:
            return abort(403, description='Użytkownik o podanej nazwie już istnieje!')
        elif userEmail:
            return abort(403, description='Konto o podanym adresie email już istnieje! prosimy o podanie innego.')
        newUser = User(
            username=registerData['username'],
            password=bcrypt.generate_password_hash(
                registerData['password']),
            email=registerData['email'],
            registered_on=datetime.now())
        token = generate_confirmation_token(newUser.email)
        db.session.add(newUser)
        send_email(
            newUser.email,
            'Aktywacja Konta',
            render_template(
                'auth/activate.html',
                confirm_url=url_for(
                    'auth.confirm_account',
                    token=token,
                    _external=True)))
        db.session.commit()
        return jsonify(message='Twoje konto zostało pomyślnie utworzone! Na adres e-mail została wysłana wiadomość z linkiem aktywacyjnym - prosimy aktywować konto.')
Beispiel #3
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('home.home_page'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User.objects(username=form.username.data).first()
        userEmail = User.objects(email=form.email.data).first()

        if user:
            flash('Podana nazwa użytkownika jest już zajęta!', 'danger')
        elif userEmail:
            return flash('Konto o podanym adresie email już istnieje! prosimy o podanie innego.', 'danger')
        newUser = User(
            username=form.username.data,
            email=form.email.data,
            password=bcrypt.generate_password_hash(
                form.password.data)).save()

        token = generate_confirmation_token(newUser.email)
        send_email(
            newUser.email,
            'Aktywacja Konta',
            render_template(
                'auth/activate.html',
                confirm_url=url_for(
                    'auth.confirm_account',
                    token=token,
                    _external=True)))
        flash('Twoje konto zostało pomyślnie utworzone! Na podany adres e-mail wyslaliśmy wiadomość z linkiem aktywacyjnym. Prosimy aktywować  swoje konto aby mieć dostęp do pełnej wersji strony', 'success')
        return redirect(url_for('home.home_page'))
    return render_template('/auth/register.html', form=form)
Beispiel #4
0
def forget_password():
    if current_user.is_authenticated:
        return redirect(url_for('home.home_page'))
    else:
        form = ResetPasswordForm()
        if form.validate_on_submit():
            user = User.objects(email=form.email.data).first()
            if user.last_change + timedelta(minutes=30) <= datetime.now():
                if user:
                    token = generate_confirmation_token(user.email)
                    send_email(
                        user.email,
                        'Zmiana hasła',
                        render_template(
                            'auth/activate.html',
                            confirm_url=url_for(
                                'auth.reset_password',
                                token=token,
                                _external=True)))
                    flash(
                        'Na podany adres email zostały wysłane dalesze instrukcje dotyczące zmiany hasła!',
                        'success')
                else:
                    flash(
                        'Do podanego adresu email nie zostało przypisane żadne konto!',
                        'danger')
            else:
                flash(
                    'Hasło można zresetować po upływie 30minut od ostatniej zmiany!',
                    'warning')
    return render_template('/auth/forgetPassword.html', form=form)
Beispiel #5
0
def auth_register():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    password = request.json.get('password', None)
    mail = request.json.get('mail', None)
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400
    if not mail:
        return jsonify({"msg": "Missing mail parameter"}), 400

    code = fn_user_add(mail, password)
    if code == 201:
        subject = '[🐒&🐖] Bienvenue chez le Singouins !'
        token = generate_confirmation_token(mail)
        url = API_URL + '/auth/confirm/' + token
        body = open("/code/data/registered.html", "r").read()
        if send(
                mail, subject,
                body.format(urllogo='[INSERT LOGO HERE]',
                            urlconfirm=url,
                            urldiscord=DISCORD_URL)):
            return jsonify({"msg": "User successfully added | mail OK"}), code
        else:
            return jsonify({"msg": "User successfully added | mail KO"}), 206
    elif code == 409:
        return jsonify({"msg": "User or Email already exists"}), code
    else:
        return jsonify({"msg": "Oops!"}), 422
Beispiel #6
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('home.home_page'))
    form = RegistrationForm()
    if form.validate_on_submit():
        newUser = User(username=form.username.data,
                       email=form.email.data,
                       password=bcrypt.generate_password_hash(
                           form.password.data),
                       registered_on=datetime.now().strftime('%m-%d-%Y'),
                       registered_time=datetime.now().strftime('%H:%M'))
        print(newUser)
        db.session.add(newUser)
        db.session.commit()

        token = generate_confirmation_token(newUser.email)
        send_email(
            newUser.email, 'Aktywacja Konta',
            render_template('auth/activate.html',
                            confirm_url=url_for('auth.confirm_account',
                                                token=token,
                                                _external=True)))
        login_user(newUser)
        flash(
            'Twoje konto zostało pomyślnie utworzone! Na podany adres e-mail wyslaliśmy wiadomość z linkiem aktywacyjnym. Prosimy aktywować  swoje konto aby mieć dostęp do pełnej wersji strony',
            'success')
        return redirect(url_for('home.home_page'))
    return render_template('/auth/register.html', form=form)
Beispiel #7
0
 def get(self):
     user = User.objects(username='******').first()
     login_user(user)
     if not current_user.is_authenticated:
         return abort(403)
     if current_user.confirmed:
         return abort(403)
     user = User.objects(username=current_user.username).first_or_404()
     token = generate_confirmation_token(user.email)
     send_email(
         user.email, 'Aktywacja Konta',
         render_template('auth/activate.html',
                         confirm_url=url_for('auth.confirm_account',
                                             token=token,
                                             _external=True)))
     return jsonify(
         message='Na twoj adres email został wysłany link potwierdzający!')
Beispiel #8
0
    def post(self):
        if not request.json:
            return abort(
                403,
                description=
                'Brakujące argumenty, prosze wypełnić wszystkie pola.')
        registerData = {
            'username': request.json['username'],
            'password': request.json['password'],
            'email': request.json['email'],
            'sex': request.json['sex']
        }
        if not registerData['username'] or not registerData['password'] or (
                not registerData['email']) or not registerData['sex']:
            return abort(
                403,
                description=
                'Brakujące argumenty, prosze wypełnić wszystkie pola.')
        user = User.objects(username=registerData['username']).first()
        userEmail = User.objects(email=registerData['email']).first()

        if user:
            return abort(
                403, description='Użytkownik o podanej nazwie już istnieje!')
        elif userEmail:
            return abort(
                403,
                description=
                'Konto o podanym adresie email już istnieje! prosimy o podanie innego.'
            )
        newUser = User(username=registerData['username'],
                       password=bcrypt.generate_password_hash(
                           registerData['password']),
                       email=registerData['email'],
                       sex=registerData['sex']).save()
        token = generate_confirmation_token(newUser.email)
        send_email(
            newUser.email, 'Aktywacja Konta',
            render_template('auth/activate.html',
                            confirm_url=url_for('auth.confirm_account',
                                                token=token,
                                                _external=True)))
        return jsonify(
            message=
            'Twoje konto zostało pomyślnie utworzone! Na adres e-mail została wysłana wiadomość z linkiem aktywacyjnym - prosimy aktywować konto.'
        )
Beispiel #9
0
    def post(self):
        data = request.form
        new_user = User(username=data['username'],
                        password_hash=User.generate_hash(data['password']),
                        email=data['email'],
                        confirmed=False)

        if User.find_by_email(data['email']):
            return {
                'message': 'Email {} already used'.format(data['email'])
            }, 409

        if User.find_by_username(data['username']):
            return {
                'message': 'User {} already exists'.format(data['username'])
            }, 409

        try:
            new_user.save_to_db()

            to_addr = new_user.email
            from_addr = current_app.config['MAIL_DEFAULT_SENDER']
            bcc_addr = current_app.config['MAIL_DEFAULT_SENDER']
            password = current_app.config['MAIL_PASSWORD']

            token = generate_confirmation_token(new_user.email)
            confirm_url = current_app.config[
                'CLIENT_BASE_URL'] + '/confirm?token=' + token

            body = render_template('user/activate.html',
                                   confirm_url=confirm_url)
            subject = "Please confirm your email"
            msg = create_email(from_addr, to_addr, bcc_addr, subject, body)
            send_email(msg, password)

            access_token = create_access_token(identity=data['username'])
            refresh_token = create_refresh_token(identity=data['username'])
            return {
                'message': 'User {} was created'.format(data['username']),
                'access_token': access_token,
                'refresh_token': refresh_token
            }
        except:
            print("Unexpected error:", sys.exc_info()[0])
            return {'message': 'Something went wrong'}, 500
Beispiel #10
0
def auth_forgotpassword():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    mail = request.json.get('mail', None)
    (code, password) = fn_forgot_password(mail)

    if code == 200:
        subject = '[🐒&🐖] Mot de passe oublié'
        token = generate_confirmation_token(mail)
        url = API_URL + '/auth/confirm/' + token
        body = open("/code/data/forgot_password.html", "r").read()
        if send(
                mail, subject,
                body.format(urllogo='[INSERT LOGO HERE]',
                            password=password,
                            urldiscord=DISCORD_URL)):
            return jsonify({"msg":
                            "Password successfully replaced | mail OK"}), code
        else:
            return jsonify({"msg":
                            "Password successfully replaced | mail KO"}), 206
    else:
        return jsonify({"msg": "Oops!"}), 422