Exemplo n.º 1
0
def password_update_by_token():
    data = request.json
    try:
        update_user = user_model.User.query.filter_by(
            username=data['username']).first()
        if update_user is not None:
            if update_user.reset_token != data[
                    'token'] or update_user.reset_token is None:
                return jsonify({'response': 'Token incorrect or expired'}), 401
            old_token = update_user.reset_token
            update_user.set_password(data['secret'])
            update_user.reset_token = None
            update_user.last_updated = datetime.utcnow()
            db.session.commit()
            try:
                send_mail(
                    update_user.email, 'Password Updated', '''Hi {},
                Your password is updated
                '''.format(update_user.name))
            except smtplib.SMTPException:
                update_user.reset_token = old_token
                db.session.commit()
                return s_vars.error_try_again, 501
            res = {
                'result':
                'Password reset link sent for user {}'.format(
                    update_user.email)
            }
            return jsonify(res), 200
        else:
            return s_vars.user_not_exist, 404
    except KeyError:
        return s_vars.bad_request, 400
Exemplo n.º 2
0
def password_reset_by_email():
    data = request.json
    if 'email' not in list(data.keys()):
        return s_vars.bad_request, 400
    update_user = user_model.User.query.filter_by(email=data['email']).first()
    if update_user is not None:
        update_user.reset_token = id_gen(25)
        update_user.last_updated = datetime.utcnow()
        db.session.commit()
        try:
            send_mail(
                update_user.email, 'Password Reset Link', '''Hi {},
            Click or open the provided URL to change your password.\n\n {}
            '''.format(
                    update_user.name,
                    f"{request.origin if request.origin is not None else 'http://www.n4nit.in'}{s_vars.front_end_prefix}password_reset/{update_user.reset_token}/{update_user.username}"
                ))
        except smtplib.SMTPException as smtp_err:
            # return jsonify({'response': 'Try again later.', 'error': str(smtp_err)})
            return s_vars.error_try_again, 501
        res = {
            'result':
            'Password reset link sent for user {}'.format(update_user.email)
        }
        return jsonify(res), 200
    else:
        return s_vars.user_not_exist, 404
Exemplo n.º 3
0
def add_user():
    data = request.json
    if data['username'] == 'public':
        return s_vars.cannot_create_user, 403
    verification_code = code_gen()
    try:
        new_user = user_model.User(name=data['name'],
                                   username=data['username'],
                                   email=data['email'],
                                   verification_code=verification_code)
        new_user.set_password(data['secret'])
        new_user.set_verification_expiry()
        db.session.add(new_user)
        db.session.commit()
        res = {'result': new_user.__repr__()}
        send_mail(data['email'], 'Welcome to N4NITIN',
                  'Verification Code: {}'.format(verification_code))
        db.session.expunge(new_user)
        db.session.close()
    except KeyError:
        return s_vars.bad_request, 400
    except exc.IntegrityError as e:
        logging.error(e)
        return s_vars.user_already_exist, 409
    except smtplib.SMTPException:
        return s_vars.mail_sending_failed, 501
    return res, 200
Exemplo n.º 4
0
def action_by_username(action_type):
    data = request.json
    if 'username' not in list(data.keys()):
        return s_vars.bad_request, 400
    auth_status, auth_user = au_ser.check_auth_token(request.headers)
    if auth_user == data['username'] and auth_user != 'public':
        update_user = user_model.User.query.filter_by(
            username=data['username']).first()
        if update_user is not None:
            msg_str = ''
            if action_type == 'deactivate':
                change_user_activation(data['username'], False)
                msg_str = ' deactivated'
            elif action_type == 'activate':
                change_user_activation(data['username'], True)
                msg_str = ' activated'
            elif action_type == 'delete':
                delete_user(data['username'])
                msg_str = ' deleted'
            elif action_type == 'verify':
                try:
                    if update_user.verification_code == data[
                            'verification_code']:
                        update_user.verified = True
                        msg_str = ' verified'
                        send_mail(update_user.email,
                                  'Account Verified at N4NITIN',
                                  'Hi, Your account has been verified')
                    else:
                        return s_vars.invalid_code, 401
                except KeyError:
                    return s_vars.bad_request, 400
                except smtplib.SMTPException:
                    return s_vars.mail_sending_failed, 501
            elif action_type == 'resend_verification':
                update_user.verification_code = code_gen()
                update_user.set_verification_expiry()
                try:
                    send_mail(
                        update_user.email, 'Welcome to N4NITIN',
                        'Verification Code: {}'.format(
                            update_user.verification_code))
                    msg_str = ', verification code resent.'
                except smtplib.SMTPException:
                    return s_vars.mail_sending_failed, 501
            else:
                return s_vars.invalid_action, 404
            update_user.last_updated = datetime.utcnow()
            db.session.commit()
            res = {
                'response': 'User \'{}\'{}'.format(update_user.username,
                                                   msg_str)
            }
            return jsonify(res), 200
        else:
            return s_vars.user_not_exist, 404
    else:
        return s_vars.not_authorized, 401
Exemplo n.º 5
0
def add_group():
    data = request.json
    try:
        auth_status, auth_user = au_ser.check_auth_token(request.headers)
        owner = auth_user
        if owner != data['username']:
            return s_vars.not_authorized, 401
        cards = Card.query.filter(Card.card_id.in_(data['card_ids'])).all()
        if len(cards) < len(set(data['card_ids'])) or len(data['card_ids']) == 0:
            return s_vars.card_not_exist, 404
        group = Group(
            owner=owner,
            group_id=id_gen(),
            title=data['title'],
            description=data['description'],
            icon_url=data['icon_url'] if 'icon_url' in list(data.keys()) else None,
        )
        db.session.add(group)
        db.session.commit()
        result = {'group': group.__repr__(), 'cards_in_group': []}
        for card_id in list(set(data['card_ids'])):
            group_card = GroupCards(group_id=group.group_id, card_id=card_id)
            db.session.add(group_card)
            db.session.commit()
            result['cards_in_group'].append(group_card.__repr__())
        try:
            user = user_model.User.query.filter_by(username=owner).first()
            send_mail(user.email, 'Successfully Created Group', '''Hi {},
            Group \'{}\' has been successfully with below cards.
            
            {}'''.format(user.name, group.title, ', '.join([card.title for card in cards])))
        except smtplib.SMTPException:
            return s_vars.mail_sending_failed, 501
        except socket.gaierror:
            return s_vars.mail_sending_failed, 502
        return jsonify({'result': result}), 200
    except KeyError:
        return s_vars.bad_request, 400
    except exc.IntegrityError:
        return jsonify({'result': 'Duplicate record'}), 409
Exemplo n.º 6
0
def add_card():
    data = request.json
    auth_status, auth_user = au_ser.check_auth_token(request.headers)
    owner = auth_user
    if len(owner) == 0:
        return s_vars.not_authorized, 401
    else:
        try:
            user = None
            if owner != 'public':
                user = user_model.User.query.filter_by(
                    username=owner, deactivated=False).first()
                if user is None:
                    return s_vars.user_not_exist, 401
                if not user.verified:
                    return s_vars.not_verified_user, 403
            short_url = data['short_url'] if 'short_url' in list(
                data.keys()) else id_gen(10)

            msg, resp_code = get_availability_su(short_url)
            if resp_code == 409:
                return msg, resp_code
            keys = list(data.keys())
            card = Card(
                created_by=owner,
                owner=owner,
                card_id=id_gen(),
                title=data['title'],
                description=data['description'],
                icon_url=data['icon_url'] if 'icon_url' in keys else None,
                short_url=short_url,
                redirect_url=data['redirect_url'],
                expiry=parser.parse(data['expiry'])
                if 'expiry' in keys else None,
            )
            db.session.add(card)
            db.session.commit()
            res = card.__repr__()
            if owner != 'public':
                send_mail(
                    user.email, 'N4NITIN - Create Request', '''Hi {0},
                You have created new shorturl with below details:
                Owner: {0},
                Title: {1},
                Description: {2},
                ShortUrl: {3},
                RedirectUrl: {4},
                Expiry: {5}
                '''.format(res['owner'], res['title'], res['description'],
                           (request.origin if request.origin is not None else
                            'http://www.n4nit.in') + '/' + short_url,
                           res['redirect_url'], res['expiry']))
            db.session.expunge(card)
            db.session.close()
        except KeyError:
            return s_vars.bad_request, 400
        except exc.IntegrityError:
            return s_vars.duplicate_record, 409
        except smtplib.SMTPException:
            return s_vars.mail_sending_failed, 501
        return jsonify(res), 200