コード例 #1
0
ファイル: server_test.py プロジェクト: ShoreoNoSure/COMP1531
def test_auth_login():
    '''test successful login'''
    urllib.request.urlopen(urllib.request.Request(f"{BASE_URL}/workspace/reset", method='POST'))
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse"), "name_first": "Jiaqi", "name_last": "Zhu"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/auth/register",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    payload = json.load(response)
    token = payload['token']
    u_id = payload['u_id']
    token = json.dumps(token).encode("utf-8")
    req = urllib.request.Request(
        f"{BASE_URL}/auth/logout",
        data=token,
        headers={"Content-Type": "application/json"},
        method='POST'
    )
    with urllib.request.urlopen(req) as response:
        payload = json.load(response)
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse")}).encode("utf-8")
    req = urllib.request.Request(
        f"{BASE_URL}/auth/login",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    )
    with urllib.request.urlopen(req) as response:
        payload = json.load(response)
    assert payload['u_id'] == u_id
コード例 #2
0
ファイル: server_test.py プロジェクト: ShoreoNoSure/COMP1531
def test_user_profile_setemail_taken():
    '''test when email is already taken'''
    #reset workspace
    urllib.request.urlopen(urllib.request.Request(f"{BASE_URL}/workspace/reset", method='POST'))
    #create a new user
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse"), "name_first": "Robbie", "name_last": "Caldwell"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/auth/register",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    #register for a second new user
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse"), "name_first": "Jiaqi", "name_last": "Zhu"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/auth/register",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    #changing the users email
    payload = json.load(response)
    token = payload["token"]
    data = json.dumps({"token": token, "email": "*****@*****.**"}).encode("utf-8")
    with pytest.raises(urllib.error.HTTPError):
        urllib.request.urlopen(urllib.request.Request(
            f"{BASE_URL}/user/profile/setemail",
            data=data,
            headers={"Content-Type": "application/json"},
            method='PUT'
        ))
コード例 #3
0
ファイル: server_test.py プロジェクト: ShoreoNoSure/COMP1531
def test_user_profile_self():
    '''test successful check in someones own profile'''
    #reset workspace
    urllib.request.urlopen(urllib.request.Request(f"{BASE_URL}/workspace/reset", method='POST'))
    #create a new user
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse"), "name_first": "Robbie", "name_last": "Caldwell"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/auth/register",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    payload = json.load(response)
    token = payload["token"]
    u_id = payload["u_id"]
    #checking the name change was successful
    response = urllib.request.urlopen(f"{BASE_URL}/user/profile?token={token}&u_id={u_id}")
    payload = json.load(response)
    assert payload == {
        "user": {
            "u_id": u_id,
            "email": "*****@*****.**",
            "name_first": "Robbie",
            "name_last": "Caldwell",
            "handle_str":get_handle("Robbie", "Caldwell"),
        }
    }
コード例 #4
0
def login():
    if request.method == "GET":
        # NuxtJS Authentication requires a user information after successfully logged in to the system
        # Strip 'Bearer: ' in "Bearer {token}" header
        token = request.headers.get("Authorization")[7:]
        payload = jwt.decode(token, SECRET_KEY, algorithms="HS256")
        return jsonify({"username": payload['username']})

    elif request.method == "POST":
        post_data = request.get_json()
        if user := User.query.filter(User.email == post_data['email']).first():
            if hash_password(post_data['password'],
                             user.password_salt).decode() == user.password:
                payload = {
                    "username": user.username,
                    "fullname": user.fullname,
                    "status": user.status
                }
                token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")
                return jsonify({"token": token.decode()})

            return jsonify(
                {"error_message": "Username & password is not matched"}), 403
        else:
            return jsonify({"error_message": "User does not exist"}), 403
コード例 #5
0
def start():
    if session.get('user'):
        return redirect(url_for('home'))
    else:
        if request.method == "POST":
            if request.form.get("action") == "login":
                return redirect(url_for('login_page'))
            elif request.form.get("action") == "register":
                return redirect(url_for('register'))
            else:
                cur = mysql.connection.cursor()
                pssw1 = random_password()
                name = "guest"
                username = random_username()
                inv_code = "NOT_REGISTERED"
                level = 0              
                password = hash_password(pssw1)
                session['logged_in'] = True
                session['admin'] = False
                session['user'] = username
                session['state'] = "clear"
                session['level'] = 0
                session['tip_date'] = "clear"
                add_user(cur, name, username, password, inv_code, level)
                cur.close()
                return redirect(url_for('intro'))

    return render_template("start.html")
コード例 #6
0
ファイル: server_test.py プロジェクト: ShoreoNoSure/COMP1531
def test_user_profile_sethandle():
    '''test successful user profile check'''
    #reset workspace
    urllib.request.urlopen(urllib.request.Request(f"{BASE_URL}/workspace/reset", method='POST'))
    #create a new user
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse"), "name_first": "Robbie", "name_last": "Caldwell"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/auth/register",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    #changing the users handle
    payload = json.load(response)
    token = payload["token"]
    data = json.dumps({"token": token, "handle_str": "Masters_Material"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/user/profile/sethandle",
        data=data,
        headers={"Content-Type": "application/json"},
        method='PUT'
    ))
    #chcking that the handle change was successful
    response = urllib.request.urlopen(f"{BASE_URL}/users/all?token={token}")
    payload = json.load(response)
    assert payload == {
        "users": [{
            "u_id": 1,
            "email": "*****@*****.**",
            "name_first": "Robbie",
            "name_last": "Caldwell",
            "handle_str":"Masters_Material",
        }]
    }
コード例 #7
0
ファイル: server_test.py プロジェクト: ShoreoNoSure/COMP1531
def test_empty_last_name():
    urllib.request.urlopen(urllib.request.Request(f"{BASE_URL}/workspace/reset", method='POST'))
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("helloworld"), "name_first": "Kool", "name_last": ""}).encode("utf-8")
    with pytest.raises(urllib.error.HTTPError):
        urllib.request.urlopen(urllib.request.Request(
            f"{BASE_URL}/auth/register",
            data=data,
            headers={"Content-Type": "application/json"},
            method='POST'
        ))
コード例 #8
0
ファイル: users.py プロジェクト: elmasria/multi-user-blog
 def register(cls, name, pw, email=None):
     """
             Hash given password
             return User object
     """
     pw_hash = helper.hash_password(name, pw)
     return cls(parent=helper.user_key(),
                username=name,
                password=pw_hash,
                email=email)
コード例 #9
0
 def login(self, username: str, raw_password: str) -> str:
     if user := self.get_user(username=username):
         if hash_password(raw_password,
                          user.password_salt).decode() == user.password:
             payload = {
                 "username": user.username,
                 "fullname": user.fullname,
                 "status": user.status
             }
             token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")
             return token.decode()
コード例 #10
0
ファイル: auth.py プロジェクト: ShoreoNoSure/COMP1531
def auth_password_reset(reset_code, new_password):
    '''This program resets a users password given a reset code'''
    data = get_data()
    if len(new_password) < 6:
        raise InputError("Invalid password, must be longer")
    for user in data['users']:
        # Check if the reset code given was an currently active for a user
        if user['reset_code'] == reset_code:
            user['password'] = str(hash_password(new_password))
            return {}
    raise InputError("Reset code incorrect")
コード例 #11
0
    def register(self, email: str, username: str, password: str) -> User:
        if self.db.find_user(username=username):
            raise Exception({"error_message": "Username is already taken"})

        if self.db.find_user(email=email):
            raise Exception({"error_message": "Email is already registered"})

        salt = randomString(32)
        hashed_password = hash_password(password, salt)
        user = User(None, username, email, None, hashed_password, salt)
        self.db.add_user(user)
        return self.get_user(username=username)
コード例 #12
0
   def init_from_request(response):
      try:
         phone       = response['phone']
         password    = hash_password(response['password'])
      except KeyError:
         raise Exception('Bad request format')
         return
      except UnicodeDecodeError:
         raise Exception('Cannot decode unicode string')
         return

      new_user = User(phone=phone, password=password)
      save_to_db(new_user)
コード例 #13
0
ファイル: server_test.py プロジェクト: ShoreoNoSure/COMP1531
def test_message_unpin():
    '''testing unpinning a message'''
    #reset workspace
    urllib.request.urlopen(urllib.request.Request(f"{BASE_URL}/workspace/reset", method='POST'))
    #register for a new user
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse"), \
        "name_first": "Sinha", "name_last": "Nawa"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/auth/register",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    #create a new channel
    payload = json.load(response)
    token = payload['token']
    data = json.dumps({"token": token, "name": "New Channel", "is_public": True}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/channels/create",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    #send a message
    payload = json.load(response)
    channel_id = payload['channel_id']
    data = json.dumps({"token": token, "channel_id": channel_id, "message": "Hello everyone"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/message/send",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    #pin a message
    payload = json.load(response)
    message_id = payload['message_id']
    data = json.dumps({"token": token, "message_id": message_id}).encode("utf-8")
    response = urllib.request.Request(
        f"{BASE_URL}/message/pin",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    )
    #unpin to a message
    data = json.dumps({"token": token, "message_id": message_id}).encode("utf-8")
    response = urllib.request.Request(
        f"{BASE_URL}/message/unpin",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    )
コード例 #14
0
    def post(self, *args, **kwargs):
        if self.current_user:
            self.redirect('/')
            return

        invite_code = self.get_argument('invite', None)
        is_valid_invite = yield tornado.gen.Task(self.check_invite,
                                                 invite_code)

        if not is_valid_invite:
            self.redirect('/register')
            return

        form = forms.RegistrationForm(self)
        if not form.validate():
            self.render("register.html", form=form)
            return

        password_hash = helper.hash_password(form.password.data)

        user = User()
        #form.populate_obj(user)
        user.email = form.email.data
        user.password_hash = password_hash
        user.screen_name = form.screen_name.data
        user.zipcode = form.zipcode.data
        user.gender = form.gender.data
        user.birth_date = datetime(form.birth_date_year.data,
                                   form.birth_date_month.data,
                                   form.birth_date_day.data)
        user.opt_in = form.subscribe.data
        user.invite_code = invite_code

        result = yield motor.Op(self.db.users.insert, user.to_dict())
        user._id = str(result)

        if invite_code:
            #Update the invite table to reflect the use
            spec = {'code': invite_code}
            update = {'$inc': {'redeemed_count': 1}}
            yield motor.Op(self.db.invites.update, spec, update)

        #TODO: Send confirmation email!

        self.login_user(user)
        self.redirect('/')
コード例 #15
0
ファイル: server.py プロジェクト: MadhuriHB/HelpMeRelocate
def register_process():
    """Process registration."""
    
    # Get form variables
    email = request.form.get("email")
    password = request.form.get("password")
    password_hashed = hash_password(password)
    zipcode = request.form.get("zipcode")
    zipcode = int(zipcode)

    new_user = User(email=email, password=password_hashed, zipcode=zipcode)

    db.session.add(new_user)
    db.session.commit()

    flash("Welcome to Help Me Relocate!")
    return redirect("/")
コード例 #16
0
ファイル: server_test.py プロジェクト: ShoreoNoSure/COMP1531
def test_channels_create():
    '''test successful creation of a channel'''
    #reset workspace
    urllib.request.urlopen(urllib.request.Request(f"{BASE_URL}/workspace/reset", method='POST'))
    #create a new user
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse"), "name_first": "Robbie", "name_last": "Caldwell"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/auth/register",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    payload = json.load(response)
    token = payload["token"]
    u_id = payload["u_id"]
    #create a new channel
    data = json.dumps({"token": token, "name": "New Channel", "is_public": True}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/channels/create",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    payload = json.load(response)
    channel_id = payload["channel_id"]
    #chcking that the channel is listed
    response = urllib.request.urlopen(f"{BASE_URL}/channel/details?token={token}&channel_id={channel_id}")
    payload = json.load(response)
    assert payload == {
        'name': 'New Channel',
        'owner_members': [
            {
                'u_id': u_id,
                'name_first': 'Robbie',
                'name_last': 'Caldwell',
            }
        ],
        'all_members': [
            {
                'u_id': u_id,
                'name_first': 'Robbie',
                'name_last': 'Caldwell',
            },
        ],
    }
コード例 #17
0
    def post(self, *args, **kwargs):
        if self.current_user:
            self.redirect('/')
            return

        invite_code = self.get_argument('invite', None)
        is_valid_invite = yield tornado.gen.Task(self.check_invite, invite_code)

        if not is_valid_invite:
            self.redirect('/register')
            return

        form = forms.RegistrationForm(self)
        if not form.validate():
            self.render("register.html", form=form)
            return

        password_hash = helper.hash_password(form.password.data)

        user = User()
        #form.populate_obj(user)
        user.email = form.email.data
        user.password_hash = password_hash
        user.screen_name = form.screen_name.data
        user.zipcode = form.zipcode.data
        user.gender = form.gender.data
        user.birth_date = datetime(form.birth_date_year.data, form.birth_date_month.data, form.birth_date_day.data)
        user.opt_in = form.subscribe.data
        user.invite_code = invite_code

        result = yield motor.Op(self.db.users.insert, user.to_dict())
        user._id = str(result)

        if invite_code:
            #Update the invite table to reflect the use
            spec = { 'code': invite_code }
            update = { '$inc' : {'redeemed_count': 1} }
            yield motor.Op(self.db.invites.update, spec, update)

        #TODO: Send confirmation email!

        self.login_user(user)
        self.redirect('/')
コード例 #18
0
ファイル: server_test.py プロジェクト: ShoreoNoSure/COMP1531
def test_standup_start():
    '''testing for standup/start'''
    #reset workspace
    urllib.request.urlopen(urllib.request.Request(f"{BASE_URL}/workspace/reset", method='POST'))
    #register for a new user
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse"), "name_first": "Jiaqi", "name_last": "Zhu"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/auth/register",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    #create a new channel
    payload = json.load(response)
    token = payload['token']
    data = json.dumps({"token": token, "name": "New Channel", "is_public": True}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/channels/create",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    #send a message later
    payload = json.load(response)
    channel_id = payload['channel_id']
    data = json.dumps({"token": token, "channel_id": channel_id, "length": 5}).encode("utf-8")
    req = urllib.request.Request(
        f"{BASE_URL}/standup/start",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    )
    start = time.time()
    with urllib.request.urlopen(req) as response:
        payload = json.load(response)
    curr_time = datetime.utcnow()
    time_stamp = curr_time.replace(tzinfo=timezone.utc).timestamp()
    time_finish = time_stamp + 5 + time.time() - start
    assert round(payload['time_finish'], 0) == round(time_finish, 0)

    response = urllib.request.urlopen(f"{BASE_URL}/standup/active?token={token}&channel_id={channel_id}")
    payload = json.load(response)
    assert payload["is_active"] is True
コード例 #19
0
def register():
    message = ""
    if request.method == 'POST':

        cur = mysql.cursor()
        valid_inv_codes = []
        stored_usernames = []
        data1 = read_invitation_codes(cur)
        data2 = read_user_data(cur)

        for d in data1:
            valid_inv_codes.append(d[1])

        for d in data2:
            stored_usernames.append(d[2])

        name = request.form['name']
        username = request.form['username']
        pssw1 = request.form['password1']
        pssw2 = request.form['password2']
        inv_code = request.form['invitation_code']
        level = 0

        if pssw1 != pssw2:

            message = "passwords don't match"
        elif inv_code not in valid_inv_codes:
            message = "wrong invitation code"
        elif username in stored_usernames:
            message = "username already exists"
        else:
            message = "You have been registered with username: "******"message.html",
                                   message=message,
                                   goto="/login")
        cur.close()
        return render_template('register.html', message=message)
    return render_template('register.html', message=message)
コード例 #20
0
ファイル: auth.py プロジェクト: ShoreoNoSure/COMP1531
def auth_register(email, password, name_first, name_last):
    '''This program registers a user'''
    data = get_data()
    # check email
    if check(email) is False:
        raise InputError(description="Invalid Email")
    # Invalid password
    if len(password) < 6:
        raise InputError(description="Invalid Password")
    # Invalid firstname
    if not name_first or len(name_first) > 50:
        raise InputError(description="Invalid First Name")
    # Invalid Lastname
    if not name_last or len(name_last) > 50:
        raise InputError(description="Invalid Last Name")
    # Email already in use
    for user in data['users']:
        if user['email'] == email:
            raise InputError(description="Email already in use")

    # New user for backend
    u_id = get_max_u_id() + 1
    # Assume that you are logged in once you register
    token = generate_token(u_id)
    new_user = {
        'u_id': u_id,
        'name_first': name_first,
        'name_last': name_last,
        'password': str(hash_password(password)),
        'email': email,
        'token': token,
        'reset_code': 0,
        'logged_in': 1,
        'handle_str': get_handle(name_first, name_last),
        'permission_id': 2,
        'profile_img_url': ''
    }
    data['users'].append(new_user)
    # Owner permision id = 1 normal memeber id = 2
    if u_id == 1:
        new_user['permission_id'] = 1
    return {"u_id": u_id, "token": token}
コード例 #21
0
    def post(self, *args, **kwargs):
        form = forms.LoginForm(self)
        if form.validate():
            #Check password
            password_hash = helper.hash_password(form.password.data)
            spec = { 'email': form.email.data, 'password_hash': password_hash }
            user_doc = yield motor.Op(self.db.users.find_one, spec)
            if user_doc:
                #Correct Password! Set cookie and redirect to home page
                user = User(**user_doc)
                self.login_user(user, form.remember.data)
                self.redirect('/')
                return
            else:
                #Somehow need to show the invalid login error.
                form.email.errors.append(True)
                form.password.errors.append(True)
                form.errors['invalid'] = True

        self.render("login.html", form=form)
コード例 #22
0
    def post(self, *args, **kwargs):
        form = forms.LoginForm(self)
        if form.validate():
            #Check password
            password_hash = helper.hash_password(form.password.data)
            spec = {'email': form.email.data, 'password_hash': password_hash}
            user_doc = yield motor.Op(self.db.users.find_one, spec)
            if user_doc:
                #Correct Password! Set cookie and redirect to home page
                user = User(**user_doc)
                self.login_user(user, form.remember.data)
                self.redirect('/')
                return
            else:
                #Somehow need to show the invalid login error.
                form.email.errors.append(True)
                form.password.errors.append(True)
                form.errors['invalid'] = True

        self.render("login.html", form=form)
コード例 #23
0
ファイル: server.py プロジェクト: MadhuriHB/HelpMeRelocate
def login_process():
    """Process login."""

    # Get form variables
    email = request.form.get("email")
    password = request.form.get("password")

    user = User.query.filter_by(email=email).first()

    if not user:
        flash("You are not registered. Please register and then Login")
        return render_template("register_form.html")

    if user.password != hash_password(password):
        flash("Incorrect password")
        return redirect("/login")

    session["user_id"] = user.user_id

    # flash("You are now Logged in")
    return redirect("/")
コード例 #24
0
ファイル: server_test.py プロジェクト: ShoreoNoSure/COMP1531
def test_send_message_later():
    '''testing for sending a message in the future'''
    #reset workspace
    urllib.request.urlopen(urllib.request.Request(f"{BASE_URL}/workspace/reset", method='POST'))
    #register for a new user
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse"), "name_first": "Jiaqi", "name_last": "Zhu"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/auth/register",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    #create a new channel
    payload = json.load(response)
    token = payload['token']
    data = json.dumps({"token": token, "name": "New Channel", "is_public": True}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/channels/create",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    #send a message later
    payload = json.load(response)
    channel_id = payload['channel_id']
    curr_time = datetime.now()
    time_stamp = curr_time.replace(tzinfo=timezone.utc).timestamp()
    data = json.dumps({"token": token, "channel_id": channel_id, "message": "Hello everyone", "time_sent": time_stamp + 5}).encode("utf-8")
    req = urllib.request.Request(
        f"{BASE_URL}/message/sendlater",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    )
    sleep(5)
    with urllib.request.urlopen(req) as response:
        json_response = json.load(response)
    assert json_response == {"message_id": 1}
コード例 #25
0
ファイル: auth.py プロジェクト: ShoreoNoSure/COMP1531
def auth_login(email, password):
    '''This program logs a user in'''
    data = get_data()
    # Check email
    if check(email) is False:
        raise InputError(description="Invalid Email")
    #Password check
    password = hash_password(password)
    for user in data['users']:
        #if found a matching email
        if user['email'] == email:
            if user['password'] != password:
                #Not correct password
                raise InputError(description="Incorrect Password")
            else:
                #if password correct
                u_id = user['u_id']
                user['logged_in'] = 1
                #generate a token
                token = generate_token(u_id)
                return {'u_id': u_id, 'token': token}
    # No matching email
    raise InputError(description="No user found with this email")
コード例 #26
0
def register():
    post_data = request.get_json()

    # Check if the username already exist
    if User.query.filter(User.email == post_data['email']).count():
        return jsonify({"error_message": "Email is already registered"}), 403

    if User.query.filter(User.username == post_data['username']).count():
        return jsonify({"error_message": "Username is already taken"}), 403

    salt = randomString(32)
    hashed_password = hash_password(post_data['password'], salt)
    new_user = User(username=post_data['username'],
                    email=post_data['email'],
                    password=hashed_password,
                    password_salt=salt)

    try:
        db.session.add(new_user)
        db.session.commit()
    except:
        db.session.rollback()

    return jsonify({"status": "OK"})
コード例 #27
0
ファイル: server_test.py プロジェクト: ShoreoNoSure/COMP1531
def test_auth_register():
    '''test successful registration'''
    urllib.request.urlopen(urllib.request.Request(f"{BASE_URL}/workspace/reset", method='POST'))
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse"), "name_first": "Jiaqi", "name_last": "Zhu"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/auth/register",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    payload = json.load(response)
    token = payload["token"]
    
    response = urllib.request.urlopen(f"{BASE_URL}/users/all?token={token}")
    payload = json.load(response)
    assert payload == {
        "users": [{
            "u_id": 1,
            "email": "*****@*****.**",
            "name_first": "Jiaqi",
            "name_last": "Zhu",
            "handle_str":get_handle("Jiaqi", "Zhu"),
        }]
    }
コード例 #28
0
    def register(self):
        fname = self.firstNameLineEdit.text()
        lname = self.lastNameLineEdit.text()
        user_name = self.userNameLineEdit.text()
        pwd = self.passwordLineEdit.text()
        c_pwd = self.confirmedPasswordLineEdit.text()
        user_type = self.userTypeComboBox.currentText()
        phone = self.phoneLineEdit.text()
        address = self.addressLineEdit.text()
        city = self.city_input.text()
        state = self.state_input.currentText()
        zipcode = self.zipcode_input.text()
        #######################check user name####################
        connection_object = __main__.connection_pool.get_connection()
        if connection_object.is_connected():
            db_Info = connection_object.get_server_info()
            print("register_user.py Connected to MySQL server: ", db_Info)
        else:
            print("register_user.py  Not Connected ")
        cursor = connection_object.cursor()

        query1 = "select count(*) from user where Username = \'" + user_name + "\';"
        cursor.execute(query1)
        result = cursor.fetchall()
        if result[0][0] != 0:
            QMessageBox.warning(self.gridLayoutWidget, "Invalid Information",
                                "This user name is registerd", QMessageBox.Yes,
                                QMessageBox.Yes)
            if (connection_object.is_connected()):
                cursor.close()
                connection_object.close()
                print("MySQL connection is closed")
            return
        if (connection_object.is_connected()):
            cursor.close()
            connection_object.close()
            print("MySQL connection is closed")
        ###################check empty or invalid#################################
        if ' ' in fname or len(fname) == 0:
            QMessageBox.warning(
                self.gridLayoutWidget, "Invalid Information",
                "First Name can not be NULL. First Name can not contain empty character",
                QMessageBox.Yes, QMessageBox.Yes)
            return

        if ' ' in lname or len(lname) == 0:
            QMessageBox.warning(
                self.gridLayoutWidget, "Invalid Information",
                "Last Name can not be NULL. Last Name can not contain empty character",
                QMessageBox.Yes, QMessageBox.Yes)
            return

        if ' ' in user_name or len(user_name) == 0:
            QMessageBox.warning(
                self.gridLayoutWidget, "Invalid Information",
                "User Name can not be NULL. User Name can not contain empty character",
                QMessageBox.Yes, QMessageBox.Yes)
            return
        # TODO: check dupicated user name
        if ' ' in pwd or len(pwd) < 8:
            QMessageBox.warning(
                self.gridLayoutWidget, "Invalid Information",
                "Password should be at least 8 characters. Password can not contain empty character",
                QMessageBox.Yes, QMessageBox.Yes)
            return

        if not pwd == c_pwd:
            QMessageBox.warning(self.gridLayoutWidget, "Invalid Information",
                                "Password and Confirmed Password don't match",
                                QMessageBox.Yes, QMessageBox.Yes)
            return

        if not isValidPhone(phone) or self.phoneExist(phone):
            QMessageBox.warning(
                self.gridLayoutWidget, "Invalid Information",
                "Invalid Phone Number or Phone Number Exists: %s" % (phone),
                QMessageBox.Yes, QMessageBox.Yes)
            return

        if not isValidZipcode(zipcode):
            QMessageBox.warning(self.gridLayoutWidget, "Invalid Information",
                                "Invalid Zipcode: %s" % (zipcode),
                                QMessageBox.Yes, QMessageBox.Yes)
            return

        #################check emails#######################################
        connection_object = __main__.connection_pool.get_connection()
        if connection_object.is_connected():
            db_Info = connection_object.get_server_info()
            print("register_user.py Connected to MySQL server: ", db_Info)
        else:
            print("register_user.py  Not Connected ")
        cursor = connection_object.cursor()

        emails = list()
        for le in self.lineEdits:
            email = le.text()
            if not email:
                continue
            query2 = "select count(*) from emails where Email = \'" + email + "\';"
            cursor.execute(query2)
            result = cursor.fetchall()
            if result[0][0] != 0:
                QMessageBox.warning(self.gridLayoutWidget,
                                    "Invalid Information",
                                    "This email is registerd: %s" % (email),
                                    QMessageBox.Yes, QMessageBox.Yes)
                if (connection_object.is_connected()):
                    cursor.close()
                    connection_object.close()
                    print("MySQL connection is closed")
                return
            if not isValidEmail(email):
                QMessageBox.warning(self.gridLayoutWidget,
                                    "Invalid Information",
                                    "Invalid Email address: %s" % (email),
                                    QMessageBox.Yes, QMessageBox.Yes)
                if (connection_object.is_connected()):
                    cursor.close()
                    connection_object.close()
                    print("MySQL connection is closed")
                return
            else:
                emails.append(email)
        print(emails)
        if (connection_object.is_connected()):
            cursor.close()
            connection_object.close()
            print("MySQL connection is closed")
        if len(emails) == 0:
            QMessageBox.warning(self.gridLayoutWidget, "Invalid Information",
                                "Input at least one email", QMessageBox.Yes,
                                QMessageBox.Yes)
            return
        ########################## store info to database##########################
        pwd = hash_password(pwd)
        query3 = "insert into user values (\'" + user_name + "\',\'" + pwd + "\'," + "\'Pending\'" + ",\'" + fname + "\',\'" + lname + "\',\'" + user_type + "\');"
        connection_object = __main__.connection_pool.get_connection()
        if connection_object.is_connected():
            db_Info = connection_object.get_server_info()
            print("register_user.py Connected to MySQL server: ", db_Info)
        else:
            print("register_user.py  Not Connected ")
        cursor = connection_object.cursor()
        cursor.execute(query3)
        #connection_object.commit()
        print(query3)
        eid = str(uuid.uuid4().fields[-1])[:9]
        query5 = "insert into employee values (\'" + user_name + "\',\'" + eid + "\',\'" + phone + "\',\'" + address + "\',\'" + city + "\',\'" + state + "\',\'" + zipcode + "\');"
        cursor.execute(query5)
        #connection_object.commit()
        print(query5)

        query6 = "insert into visitor values (\'" + user_name + "\')"
        cursor.execute(query6)
        print(query6)

        if user_type == "Manager":
            query7 = "insert into manager values(\'" + user_name + "\',\'Manager\')"
        elif user_type == "Staff":
            query7 = "insert into staff values(\'" + user_name + "\',\'Staff\')"
        cursor.execute(query7)

        for email in emails:
            query4 = "insert into emails values ( \'" + user_name + "\',\'" + email + "\');"
            cursor.execute(query4)
            print(query4)

        connection_object.commit()
        if (connection_object.is_connected()):
            cursor.close()
            connection_object.close()
            print("MySQL connection is closed")
コード例 #29
0
ファイル: server_test.py プロジェクト: ShoreoNoSure/COMP1531
    assert payload == {
        "users": [{
            "u_id": 1,
            "email": "*****@*****.**",
            "name_first": "Robbie",
            "name_last": "Caldwell",
            "handle_str":"Masters_Material",
        }]
    }

def test_user_profile_sethandle_taken():
        '''test when handle is already taken'''
    #reset workspace
    urllib.request.urlopen(urllib.request.Request(f"{BASE_URL}/workspace/reset", method='POST'))
    #create a new user
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse"), "name_first": "Robbie", "name_last": "Caldwell"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/auth/register",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    #register for a second new user
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse"), "name_first": "Jiaqi", "name_last": "Zhu"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/auth/register",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    #changing the users handle
コード例 #30
0
    def register(self):
        fname = self.firstNameLineEdit.text()
        lname = self.lastNameLineEdit.text()
        user_name = self.usernameLineEdit.text()
        pwd = self.passwordLineEdit.text()
        c_pwd = self.confirmPasswordLineEdit.text()
        #######################check user name####################
        connection_object = __main__.connection_pool.get_connection()
        if connection_object.is_connected():
            db_Info = connection_object.get_server_info()
            print("register_user.py Connected to MySQL server: ", db_Info)
        else:
            print("register_user.py  Not Connected ")
        cursor = connection_object.cursor()

        query1 = "select count(*) from user where Username = \'" + user_name + "\';"
        cursor.execute(query1)
        result = cursor.fetchall()
        if result[0][0] != 0:
            QMessageBox.warning(self.gridLayoutWidget, "Invalid Information",
                                "This user name is registerd", QMessageBox.Yes,
                                QMessageBox.Yes)
            if (connection_object.is_connected()):
                cursor.close()
                connection_object.close()
                print("MySQL connection is closed")
            return
        if (connection_object.is_connected()):
            cursor.close()
            connection_object.close()
            print("MySQL connection is closed")
        ###################check empty or invalid#################################
        if ' ' in fname or len(fname) == 0:
            QMessageBox.warning(
                self.gridLayoutWidget, "Invalid Information",
                "First Name can not be NULL. First Name can not contain empty character",
                QMessageBox.Yes, QMessageBox.Yes)
            return

        if ' ' in lname or len(lname) == 0:
            QMessageBox.warning(
                self.gridLayoutWidget, "Invalid Information",
                "Last Name can not be NULL. Last Name can not contain empty character",
                QMessageBox.Yes, QMessageBox.Yes)
            return

        if ' ' in user_name or len(user_name) == 0:
            QMessageBox.warning(
                self.gridLayoutWidget, "Invalid Information",
                "User Name can not be NULL. User Name can not contain empty character",
                QMessageBox.Yes, QMessageBox.Yes)
            return
        # TODO: check dupicated user name
        if ' ' in pwd or len(pwd) < 8:
            QMessageBox.warning(
                self.gridLayoutWidget, "Invalid Information",
                "Password should be at least 8 characters. Password can not contain empty character",
                QMessageBox.Yes, QMessageBox.Yes)
            return

        if not pwd == c_pwd:
            QMessageBox.warning(self.gridLayoutWidget, "Invalid Information",
                                "Password and Confirmed Password don't match",
                                QMessageBox.Yes, QMessageBox.Yes)
            return
        #################check emails#######################################
        connection_object = __main__.connection_pool.get_connection()
        if connection_object.is_connected():
            db_Info = connection_object.get_server_info()
            print("register_user.py Connected to MySQL server: ", db_Info)
        else:
            print("register_user.py  Not Connected ")
        cursor = connection_object.cursor()

        emails = list()
        for le in self.lineEdits:
            email = le.text()
            if not email:
                continue
            query2 = "select count(*) from emails where Email = \'" + email + "\';"
            cursor.execute(query2)
            result = cursor.fetchall()
            if result[0][0] != 0:
                QMessageBox.warning(self.gridLayoutWidget,
                                    "Invalid Information",
                                    "This email is registerd: %s" % (email),
                                    QMessageBox.Yes, QMessageBox.Yes)
                if (connection_object.is_connected()):
                    cursor.close()
                    connection_object.close()
                    print("MySQL connection is closed")
                return
            if not isValidEmail(email):
                QMessageBox.warning(self.gridLayoutWidget,
                                    "Invalid Information",
                                    "Invalid Email address: %s" % (email),
                                    QMessageBox.Yes, QMessageBox.Yes)
                if (connection_object.is_connected()):
                    cursor.close()
                    connection_object.close()
                    print("MySQL connection is closed")
                return
            else:
                emails.append(email)
        print(emails)
        if (connection_object.is_connected()):
            cursor.close()
            connection_object.close()
            print("MySQL connection is closed")
        if len(emails) == 0:
            QMessageBox.warning(self.gridLayoutWidget, "Invalid Information",
                                "Input at least one email", QMessageBox.Yes,
                                QMessageBox.Yes)
            return
        ########################## store info to database##########################
        pwd = hash_password(pwd)
        query3 = "insert into user values (\'" + user_name + "\',\'" + pwd + "\'," + "\'Pending\'" + ",\'" + fname + "\',\'" + lname + "\',\'User\');"
        connection_object = __main__.connection_pool.get_connection()
        if connection_object.is_connected():
            db_Info = connection_object.get_server_info()
            print("register_user.py Connected to MySQL server: ", db_Info)
        else:
            print("register_user.py  Not Connected ")
        cursor = connection_object.cursor()
        cursor.execute(query3)
        #connection_object.commit()
        print(query3)

        for email in emails:
            query4 = "insert into emails values ( \'" + user_name + "\',\'" + email + "\');"
            cursor.execute(query4)
            #connection_object.commit()
            print(query4)
        connection_object.commit()
        if (connection_object.is_connected()):
            cursor.close()
            connection_object.close()
            print("MySQL connection is closed")

        QMessageBox.information(self.label, "Operation Success",
                                "Operation Success", QMessageBox.Yes)
コード例 #31
0
ファイル: server_test.py プロジェクト: ShoreoNoSure/COMP1531
def test_channels_list():
    '''test successful list of all channels'''
    #reset workspace
    urllib.request.urlopen(urllib.request.Request(f"{BASE_URL}/workspace/reset", method='POST'))
    #create a new user
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse"), "name_first": "Robbie", "name_last": "Caldwell"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/auth/register",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    payload = json.load(response)
    token1 = payload["token"]
    u_id = payload["u_id"]
    #create a second user
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse"), "name_first": "Sinha", "name_last": "Nawa"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/auth/register",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    payload = json.load(response)
    token2 = payload["token"]
    #create a new channel
    data = json.dumps({"token": token1, "name": "New Channel", "is_public": True}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/channels/create",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    payload = json.load(response)
    channel_id1 = payload["channel_id"]
    #create a second channel
    data = json.dumps({"token": token2, "name": "Here We Go Again", "is_public": True}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/channels/create",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    payload = json.load(response)
    channel_id2 = payload["channel_id"]
    #create a third channel
    data = json.dumps({"token": token1, "name": "Another One", "is_public": True}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/channels/create",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    payload = json.load(response)
    channel_id3 = payload["channel_id"]
    #chcking that the channel is listed
    response = urllib.request.urlopen(f"{BASE_URL}/channels/list?token={token1}")
    payload = json.load(response)
    assert payload == {
        'channels': [
            {
                'channel_id': channel_id1,
                'name': 'New Channel',
            },
            {
                'channel_id': channel_id3,
                'name': 'Another One',
            },
        ],
    }
コード例 #32
0
                                                  password='',
                                                  use_pure=True)
    connection_object = connection_pool.get_connection()
    if connection_object.is_connected():
        info = connection_object.get_server_info()
        print("Connected to MySQL server: ", info)
    else:
        print("Database not connected")

sql = "select Username,Password from user;"

connection_object = connection_pool.get_connection()
if connection_object.is_connected():
    db_Info = connection_object.get_server_info()
    print("user_login.py login() Connected to MySQL server: ", db_Info)
else:
    print("user_login.py login() Not Connected ")
cursor = connection_object.cursor()
cursor.execute(sql)
result = cursor.fetchall()
for row in result:
    user_name, pwd = row
    pwd = hash_password(pwd)
    sql = "update user set Password = \'" + pwd + "\' where Username = \'" + user_name + "\';"
    cursor.execute(sql)
connection_object.commit()
if (connection_object.is_connected()):
    cursor.close()
    connection_object.close()
    print("MySQL connection is closed")
コード例 #33
0
ファイル: server_test.py プロジェクト: ShoreoNoSure/COMP1531
def test_channel_messages():
    '''test successful removal as an owner to a member in a channel
    Note that this will always be off by a couple ms but everything else matches'''
    #reset workspace
    urllib.request.urlopen(urllib.request.Request(f"{BASE_URL}/workspace/reset", method='POST'))
    #create a new user
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse"), "name_first": "Robbie", "name_last": "Caldwell"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/auth/register",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    payload = json.load(response)
    token = payload["token"]
    u_id = payload["u_id"]
    #create a new channel
    data = json.dumps({"token": token, "name": "New Channel", "is_public": True}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/channels/create",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    payload = json.load(response)
    channel_id = payload["channel_id"]
    data = json.dumps({"token": token, "channel_id": channel_id, "message": "Hello World"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/message/send",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    curr_time = datetime.now()
    timestamp1 = curr_time.replace(tzinfo=timezone.utc).timestamp()
    payload = json.load(response)
    message_id1 = payload["message_id"]
    data = json.dumps({"token": token, "channel_id": channel_id, "message": "Yes Please"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/message/send",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    curr_time = datetime.now()
    timestamp2 = curr_time.replace(tzinfo=timezone.utc).timestamp()
    payload = json.load(response)
    message_id2 = payload["message_id"]
    response = urllib.request.urlopen(f"{BASE_URL}/channel/messages?token={token}&channel_id={channel_id}&start=0")
    payload = json.load(response)
    assert payload == {
        'messages': [
            {
                'message_id': message_id2,
                'u_id': u_id,
                'message': 'Yes Please',
                'time_created': timestamp2,
            },
            {
                'message_id': message_id1,
                'u_id': u_id,
                'message': 'Hello World',
                'time_created': timestamp1,
            }
        ],
        'start': 0,
        'end': -1,
    }
コード例 #34
0
ファイル: server_test.py プロジェクト: ShoreoNoSure/COMP1531
def test_channel_removeowner():
    '''test successful removal as an owner to a member in a channel'''
    #reset workspace
    urllib.request.urlopen(urllib.request.Request(f"{BASE_URL}/workspace/reset", method='POST'))
    #create a new user
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse"), "name_first": "Robbie", "name_last": "Caldwell"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/auth/register",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    payload = json.load(response)
    token1 = payload["token"]
    u_id1 = payload["u_id"]
    #create a new channel
    data = json.dumps({"token": token1, "name": "New Channel", "is_public": True}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/channels/create",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    payload = json.load(response)
    channel_id = payload["channel_id"]
    #create a second user
    data = json.dumps({"email": "*****@*****.**", "password": hash_password("ilovecse"), "name_first": "Sinha", "name_last": "Nawa"}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/auth/register",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    payload = json.load(response)
    token2 = payload["token"]
    u_id2 = payload["u_id"]
    #making the second user an owner
    data = json.dumps({"token": token1, "channel_id": channel_id, "u_id": u_id2}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/channel/addowner",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    #chcking that the second user was added to the channel as an owner
    response = urllib.request.urlopen(f"{BASE_URL}/channel/details?token={token1}&channel_id={channel_id}")
    payload = json.load(response)
    assert payload == {
        'name': 'New Channel',
        'owner_members': [
            {
                'u_id': u_id1,
                'name_first': 'Robbie',
                'name_last': 'Caldwell',
            },
            {
                'u_id': u_id2,
                'name_first': 'Sinha',
                'name_last': 'Nawa',
            }
        ],
        'all_members': [
            {
                'u_id': u_id1,
                'name_first': 'Robbie',
                'name_last': 'Caldwell',
            },
            {
                'u_id': u_id2,
                'name_first': 'Sinha',
                'name_last': 'Nawa',
            }
        ],
    }
    #removing the second user as an owner
    data = json.dumps({"token": token1, "channel_id": channel_id, "u_id": u_id2}).encode("utf-8")
    response = urllib.request.urlopen(urllib.request.Request(
        f"{BASE_URL}/channel/removeowner",
        data=data,
        headers={"Content-Type": "application/json"},
        method='POST'
    ))
    #chcking that the second user was removed as an owner
    response = urllib.request.urlopen(f"{BASE_URL}/channel/details?token={token1}&channel_id={channel_id}")
    payload = json.load(response)
    assert payload == {
        'name': 'New Channel',
        'owner_members': [
            {
                'u_id': u_id1,
                'name_first': 'Robbie',
                'name_last': 'Caldwell',
            },
        ],
        'all_members': [
            {
                'u_id': u_id1,
                'name_first': 'Robbie',
                'name_last': 'Caldwell',
            },
            {
                'u_id': u_id2,
                'name_first': 'Sinha',
                'name_last': 'Nawa',
            }
        ],
    }