Skip to content

Commit

Permalink
[CE-105] Add user login support for user dashboard
Browse files Browse the repository at this point in the history
Support user login for user dashboard.
Add balance in user models

Change-Id: I0fb3238b73ed18e513eef41f0463a6055273f7e7
Signed-off-by: Haitao Yue <hightall@me.com>
  • Loading branch information
hightall committed Aug 13, 2017
1 parent 6991d68 commit b9ee96c
Show file tree
Hide file tree
Showing 11 changed files with 131 additions and 30 deletions.
15 changes: 14 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,17 @@ services:
- BACKEND=dashboard
- PORT=8080
- USERNAME=admin
- PASSWORD=pass
- PASSWORD=pass

user-dashboard:
build:
context: user-dashboard
image: cello-user-dashboard
container_name: user-dashboard
links:
- mongo:dashboard_mongo
- dashboard
ports:
- "8081:8080"
environment:
- SV_BaseURL=http://dashboard:8080/api/auth/
39 changes: 34 additions & 5 deletions src/resources/auth_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,16 @@ def register():

try:
user = User(username, password)
user.save()
return make_ok_resp(code=CODE_CREATED)
user_id = user.save()
user = user.get_by_id(user_id)
data = {
"username": user.username,
"apikey": str(user.id),
"isActivated": user.active,
"balance": user.balance,
"success": True
}
return make_ok_resp(code=CODE_CREATED, data=data)
except Exception as exc:
logger.info("exc %s", exc)
return make_fail_resp(error="register failed")
Expand All @@ -59,11 +67,12 @@ def login():
user_obj = User()
try:
user = user_obj.get_by_username_w_password(username)
if user.is_admin() and \
bcrypt.checkpw(password.encode('utf8'),
bytes(user.password.encode())):
if bcrypt.checkpw(password.encode('utf8'),
bytes(user.password.encode())):
login_user(user)
user_id = str(user.id)
return make_ok_resp(data={'success': True,
'id': user_id,
'next': url_for('bp_index.show')},
code=CODE_CREATED)
else:
Expand All @@ -77,3 +86,23 @@ def login():
def logout():
logout_user()
return redirect(url_for('bp_index.show'))


@bp_auth_api.route('/user/account/<user_id>', methods=['GET'])
def account(user_id):
logger.info("in account api {}".format(user_id))
if not user_id:
return make_fail_resp(error="no user id", data={"success": False})
user_obj = User()
user = user_obj.get_by_id(user_id)
if not user:
return make_fail_resp(error="no such user", data={"success": False})

data = {
"username": user.username,
"apikey": str(user.id),
"isActivated": user.active,
"balance": user.balance
}

return make_ok_resp(data=data)
1 change: 1 addition & 0 deletions src/resources/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ class User(Document):
isAdmin = BooleanField(default=False)
role = IntField(default=COMMON_USER)
timestamp = DateTimeField(default=datetime.datetime.now)
balance = IntField(default=0)
16 changes: 11 additions & 5 deletions src/resources/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@

class User(UserMixin):
def __init__(self, username=None, password=None, active=True,
is_admin=False, role=None, id=None):
is_admin=False, role=None, id=None, balance=0):
self.username = username
self.password = password
self.active = active
self.isAdmin = is_admin
self.role = role
self.id = None
self.balance = balance

def is_active(self):
return self.active
Expand All @@ -35,6 +36,7 @@ def save(self):
password=self.password,
active=self.active,
role=self.role,
balance=self.balance,
isAdmin=self.isAdmin)
new_user.save()
self.id = new_user.id
Expand All @@ -47,6 +49,7 @@ def get_by_username(self, username):
self.username = dbUser.username
self.active = dbUser.active
self.id = dbUser.id
self.balance = dbUser.balance
return self
else:
return None
Expand All @@ -62,6 +65,7 @@ def get_by_username_w_password(self, username):
self.password = dbUser.password
self.id = dbUser.id
self.isAdmin = dbUser.isAdmin
self.balance = dbUser.balance
return self
else:
logger.info("not get user")
Expand All @@ -71,15 +75,17 @@ def get_by_username_w_password(self, username):
return None

def get_by_id(self, id):
dbUser = models.User.objects.with_id(id)
if dbUser:
try:
dbUser = models.User.objects.get(id=id)
except Exception:
return None
else:
self.username = dbUser.username
self.active = dbUser.active
self.id = dbUser.id
self.balance = dbUser.balance

return self
else:
return None


class Anonymous(AnonymousUserMixin):
Expand Down
6 changes: 5 additions & 1 deletion src/resources/user_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ def list_user():
"isAdmin": user.isAdmin,
"role": user.role,
"active": user.active,
"balance": user.balance,
"timestamp": time.mktime(user.timestamp.timetuple())
} for user in users]

Expand Down Expand Up @@ -87,13 +88,14 @@ def create_user():

username, password = r.form["username"], r.form["password"]
role, active = int(r.form["role"]), r.form["active"]
balance = int(r.form["balance"])
active = active == "true"
salt = app.config.get("SALT", b"")
password = bcrypt.hashpw(password.encode('utf8'), bytes(salt.encode()))

try:
user = User(username, password, is_admin=role == ADMIN,
role=role, active=active)
role=role, active=active, balance=balance)
user.save()
return make_ok_resp(code=CODE_CREATED)
except Exception as exc:
Expand All @@ -112,11 +114,13 @@ def update_user(user_id):
return make_fail_resp(error=error_msg, data=r.form)

username, role = r.form["username"], int(r.form["role"])
balance = int(r.form["balance"])
active = r.form["active"]
active = active == "true"
try:
UserModel.objects(id=user_id).update(set__username=username,
set__active=active,
set__balance=balance,
set__role=role, upsert=True)
except Exception as exc:
error_msg = exc.message
Expand Down
8 changes: 7 additions & 1 deletion src/themes/basic/templates/users.html
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ <h2 class="page-header">Users: {{ items_count }}
<v-form-item label="Role" :label-col="labelCol" :wrapper-col="wrapperCol" prop="role">
<v-select v-model="userForm.role" placeholder="Please select a role" notfound="has no role" :data="roles"></v-select>
</v-form-item>
<v-form-item label="Blue Points" :label-col="labelCol" :wrapper-col="wrapperCol" prop="balance">
<v-input-number v-model="userForm.balance" :min="0" :max="9999"></v-input-number>
</v-form-item>
<v-form-item label="Active" :label-col="labelCol" :wrapper-col="wrapperCol" props="active">
<v-switch v-model="userForm.active"></v-switch>
</v-form-item>
Expand Down Expand Up @@ -80,7 +83,8 @@ <h2 class="page-header">Users: {{ items_count }}
username: '',
password: '',
role: 0,
active: true
active: true,
balance: 0
},
visible: false,
method: 'create',
Expand Down Expand Up @@ -127,6 +131,7 @@ <h2 class="page-header">Users: {{ items_count }}
columns: [
{title:"User Name", field:'name'},
{title:"Role", field:'role', sort: true},
{title:"Balance", field:'balance', sort: true},
{title:"Create Time", field:'timestamp', sort: true},
{title:"Operation", field: 'id'}
],
Expand Down Expand Up @@ -192,6 +197,7 @@ <h2 class="page-header">Users: {{ items_count }}
username: item.name,
active: item.active,
password: item.password,
balance: item.balance,
role: item.role
}
this.currentUser = item;
Expand Down
2 changes: 1 addition & 1 deletion user-dashboard/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ RUN mkdir -p /usr/app/src
COPY . /usr/app/src
RUN r.js -o /usr/app/src/build.js
WORKDIR /usr/app/built
RUN npm install && npm cache clean
RUN npm install && npm cache clean --force
EXPOSE 8080
CMD ["npm", "start"]
25 changes: 25 additions & 0 deletions user-dashboard/docker-compose-dev.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
version: "2"

# Copyright IBM Corp., All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#
services:
dashboard:
image: node
container_name: user-dashboard
external_links:
- mongodb:dashboard_mongo
ports:
- "8081:8080"
volumes:
- ./:/usr/app/src
environment:
- DEBUG=node:*
- SV_BaseURL=http://9.186.50.245:8080/api/auth/
command: bash -c "cd /usr/app/src && ./node_modules/.bin/nodemon app.js"
# mongodb:
# image: mongo
# container_name: mongo
# ports:
# - "27017:27017"
12 changes: 12 additions & 0 deletions user-dashboard/docker-compose-npm-install.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
version: "2"

# Copyright IBM Corp., All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#
services:
install-npm:
image: node
volumes:
- ./:/usr/app/src
command: bash -c "cd /usr/app/src && npm install && npm install requirejs && npm install nodemon"
36 changes: 20 additions & 16 deletions user-dashboard/modules/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,16 @@ user.prototype = {
account: function(apikey) {
return new Promise(function(resolve, reject) {
rp({
uri: this.BaseURL + "user/account/apikey/" + apikey,
uri: this.BaseURL + "user/account/" + apikey,
json: true
}).then(function(response) {
const {username, apikey, isActivated, balance} = response.data;
resolve({
success: true,
username: response.username,
apikey: response.apikey,
isActivated: response.isActivated,
balance: response.balance
username,
apikey,
isActivated,
balance
});
}).catch(function(err) {
reject({
Expand All @@ -39,17 +40,17 @@ user.prototype = {
return new Promise(function(resolve, reject) {
rp({
method: "POST",
uri: this.BaseURL + "user/account/validate",
body: {
uri: this.BaseURL + "login",
formData: {
username: name,
passwd: password
password: password
},
json: true
}).then(function(response) {
if (response.success) {
if (response.data.success) {
resolve({
success: true,
apikey: response.description
apikey: response.data.id
});
} else {
var e = new Error(response.description);
Expand All @@ -69,18 +70,21 @@ user.prototype = {
return new Promise(function(resolve, reject) {
rp({
method: "POST",
uri: this.BaseURL + "user/account",
body: {
uri: this.BaseURL + "register",
formData: {
username: name,
passwd: password,
apikey: apikey
password: password
},
json: true
}).then(function(response) {
if (response.success) {
if (response.data.success) {
const {username, apikey, isActivated, balance} = response.data;
resolve({
success: true,
apikey: apikey
apikey: apikey,
username,
isActivated,
balance
});
} else {
var e = new Error(response.description);
Expand Down
1 change: 1 addition & 0 deletions user-dashboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"multer-gridfs-storage": "^1.1.1",
"node-uuid": "^1.4.8",
"pug": "^2.0.0-rc.1",
"winston": "^2.3.1",
"request": "^2.81.0",
"request-promise": "^4.2.0"
},
Expand Down

0 comments on commit b9ee96c

Please sign in to comment.