Exemple #1
0
def login():
    u = User.login(request.form.get("email"), request.form.get("password"))
    if u is not None:
        session["email"] = request.form.get("email")
        session["current_user"] = User.find_by_email(session["email"]).__dict__
        session["current_user"]["username"] = session["email"]
        session["root"] = SYS_ROOT + "/" + u.username + "/"
        if not os.path.isdir(session["root"]):
            os.mkdir(session["root"])
        return jsonify(**{"user": u.__dict__})
    else:
        return render_error("Login Error")
Exemple #2
0
def person_handler(cls=None):
    if not is_login(session):
        flash('Please log in and see', 'error')
        return render_template('login.html')
    if cls is None:
        flash('The class id invalid', 'error')
        return render_template('_400.html')
    users = User.find_by_condition(db, _class=cls)
    return render_template('person.html', users=users)
Exemple #3
0
def user_handler(uid=None):
    if not is_login(session):
        flash('Please log in before', 'error')
        return render_template('login.html')
    if uid is None or len(uid) <= 0:
        uid = session['_user']
    user = User.find_user(db, uid=uid)
    if is_current_user(session['_user'], uid):
        return render_template('user.html', user=user)
    return render_template('_profile.html', user=user)
Exemple #4
0
def profile_handler(uid=None):
    if not is_login(session):
        return render_template('login.html')
    if request.method == 'GET':
        user = User.find_user(db, uid=uid)
        if is_current_user(session['_user'], uid):
            logger.debug('current user %s,uid user %s', session['_user'], uid)
            if user.path is None:
                return render_template('profile.html', user=user)
            logger.info("Find the user %s", user.__dict__)
            return render_template('user.html', user=user)
        return render_template('_profile.html', user=user)
    f = request.files['file']
    fn = secure_filename(f.filename)
    if not os.path.exists(os.path.join(UPLOAD, uid)):
        os.makedirs(os.path.join(UPLOAD, uid))
    p = os.path.join(os.path.join(UPLOAD, uid), fn)
    f.save(p)
    db.update({'uid': uid}, path=p, _company=request.form['_company'], _address=request.form['_address'])
    return render_template('user.html', user=User.find_user(db, uid=uid))
Exemple #5
0
def upload_users_from_file(file_='./userlist.csv'):
    column = ('account', 'passwd', 'country')
    for line in open(file_).readlines():
        values = line.split()
        print(values)
        mapping = zip(column, values)
        kwargs = dict(mapping)
        user = User(**kwargs)
        session.add(user)

    session.commit()
Exemple #6
0
def register():
    if session.get("current_user"):
        return render_error("You have registered.")
    import smtplib

    email = request.form.get("email")
    password = request.form.get("password")
    u = User.find_one(username=email)
    if u:
        return render_error("You has already registered.")

    u = User(email=email,
             username=email,
             password=User.encrypt(password),
             code=User.encrypt("%s code %s" % (email, password))).save()

    if hasattr(u, u.Meta.primary):
        session["current_user"] = u.__dict__
        sender = "*****@*****.**"
        recivers = [email, ]
        smtp_obj = smtplib.SMTP("smtp.abillist.com", 25)
        smtp_obj.login(sender, "1008_not")
        subject = "Account Active Mail"
        html = """
                Click <a href='http://%s/user/active?uid=%s&code=%s'>http://%s/user/active?uid=%s&code=%s</a> to active your account.
                <br> Your password: %s
               """ % ("sys.abillist.com", str(u.m_id), u.code, "sys.abillist.com", str(u.m_id), u.code, password)
        message = "\r\n".join([
            "From: " + sender,
            "MIME-Version: 1.0",
            "Content-type: text/html",
            "Subject: " + subject,
            "\r\n",
            html
        ])
        smtp_obj.sendmail(sender, recivers, message)
        return jsonify(**{"user": u.__dict__})
    else:
        return render_error("Register Error.")
Exemple #7
0
def users_create():
    data = request.get_json()

    with db_manager.session_scope() as session:
        # Verify that a user with the same email doesn't exist
        users = session.query(User).filter(User.email == data['email']).all()
        if users:
            return api_error(api_result_code=ApiErorrCode.USER_EXISTS,
                             error_message="User {} already exists".format(
                                 data['email']))

        # Create the user
        hashed_pass, salt = auth.pass_to_hash(data['password'])
        user = User(name=data['name'],
                    email=data.get('email', None),
                    password=hashed_pass,
                    salt=salt,
                    level=data['level'])
        session.add(user)
        session.commit()

        return jsonify(user.to_dict())
Exemple #8
0
def login():
    if request.method == 'GET':
        return render_template('login.html')
    if is_login(session):
        user = User.find_user(db, _user=request.form['_user'])
        if getattr(user, 'path', None) is not None:
            return render_template('user.html', user=user)
        flash('Sign up ok!Please compelete your infromation', 'warning')
        return render_template('profile.html', user=user)
    user = validate_user(request.form['_user'], request.form['_password'])
    if user is None:
        flash("Invalid username/password or the user does not exist", 'error')
        return render_template('login.html')
    session['_user'] = user.uid
    if getattr(user, 'path', None) is None:
        return render_template('profile.html', user=user)
    return render_template('user.html', user=user)
Exemple #9
0
def active():
    uid = request.args.get("uid")
    code = request.args.get("code")
    u = User.find_by_id(int(uid))
    if not u:
        return render_error("Account not exists.")
    if code == u.code:
        u.enable = True
        u.save()
    if u.enable:
        session["email"] = u.username
        session["current_user"] = u.__dict__
        session["root"] = SYS_ROOT + "/" + u.username + "/"
        if not os.path.isdir(session["root"]):
            os.mkdir(session["root"])
        return redirect("")
    return render_error("Active Failed!")
Exemple #10
0
def find_user(username, password):
    user = User.find_user(db, _user=username, _password=password)
    return user
Exemple #11
0
        return render_template('profile.html', user=user)
    return render_template('user.html', user=user)


@app.route('/signup', methods=['GET', 'POST'])
def signup():
    if request.method == 'GET':
        return render_template('signup.html')
    uid = str(general_uid())
    try:
        db.insert(uid=[uid], datetime=[time.time()], **request.form)
    except ValueError, e:
        logger.error("error message %s", str(e))
        flash("The phone was sign up,please sign in or find the password", 'error')
        return render_template('login.html')
    user = User.covert(uid=[uid], **request.form)
    session['_user'] = uid
    flash('Sign up ok ! Please complete your information', 'warning')
    return render_template('profile.html', user=user)


@app.route('/profile/<uid>', methods=['GET', 'POST'])
@app.errorhandler(500)
def profile_handler(uid=None):
    if not is_login(session):
        return render_template('login.html')
    if request.method == 'GET':
        user = User.find_user(db, uid=uid)
        if is_current_user(session['_user'], uid):
            logger.debug('current user %s,uid user %s', session['_user'], uid)
            if user.path is None:
Exemple #12
0
from mongoengine import connect
from mongoengine.errors import NotUniqueError
from orm.user import User

connect(
    db='project1',
    host='localhost',
    port=27017,
    username='******',
    password='******',
    authentication_source='admin'
)

try:
    user = User(email='*****@*****.**')
    user.first_name = 'Paris'
    user.last_name = 'Nakita Kejser'
    user.save()
except NotUniqueError as e:
    print('E-mail allready found')
Exemple #13
0
from mongoengine import connect
from orm.user import User

connect(
    db='project1',
    host='localhost',
    port=27017,
    username='******',
    password='******',
    authentication_source='admin'
)

# Static params field updater
user = User.objects(email='*****@*****.**')
user.update(first_name='New Paris', last_name='Nakita Kejser')

# Dynamic params field updater
user2 = User.objects(email='*****@*****.**')
fields = {
    'first_name': 'Secound Test',
    'last_name': 'Frist Last Name'
}
user2.update(**fields)

Exemple #14
0
import base64
import hashlib
import json
import datetime
import orm
from orm.user import User

# for item in orm.execute("SELECT * FROM user WHERE id=  %d" % (22,)):
#     print(type(item["date_created"]))
from sson import json_util

# print(User.find_by_id(22).username)
#
print User.login(email="*****@*****.**", password="******")

# print(json.dumps({
#     "Hello": "World",
#     "now": datetime.datetime.now()
# }, default=json_util.default))


# print("//s//sdfg//sdfg/sdfg/er".replace("//", "/", 1))
# print(({"Hello": "World"}).keys())

u = User(
    id=40,
    username="******",
    email="*****@*****.**",
    password="******",
    code="asdfawer543rfaeee")