From c0109393f538d4cb19e3c925c1e56bb73c2b722d Mon Sep 17 00:00:00 2001 From: Shin Date: Thu, 22 Feb 2018 12:09:15 +0000 Subject: [PATCH 01/54] Add primitive database --- src/service/model.py | 40 +++++++++++++++++++++++++++++++++++++ src/service/secretdiary.db | Bin 0 -> 4096 bytes 2 files changed, 40 insertions(+) create mode 100644 src/service/model.py create mode 100644 src/service/secretdiary.db diff --git a/src/service/model.py b/src/service/model.py new file mode 100644 index 0000000..61bb53c --- /dev/null +++ b/src/service/model.py @@ -0,0 +1,40 @@ +import os +import sys +from sqlalchemy import Column, ForeignKey, Integer, String, Date,Boolean +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import relationship +from sqlalchemy import create_engine +from passlib.apps import custom_app_context as pwd_context + +Base = declarative_base() + +class User(Base): + __tablename__='user' + + id=Column(Integer,primary_key=True) + username=Column(String(32),index=True,nullable=False) + password_hash=Column(String(64)) + fullname=Column(String(32),nullable=False) + age=Column(Integer) + + def hash_password(self,password): + self.password_hash=pwd_context.encrypt(password) + + def verify_password(self,password): + return pwd_context.verify(password,self.password_hash) + +class Diary(Base): + __tablename__='diary' + + id=Column(Integer,primary_key=True) + title=Column(String(100),nullable=False) + publish_date=Column(Date,nullable=False) + public = Column(Boolean,nullable=False) + text=Column(String,nullable=False) + + user_id=Column(Integer,ForeignKey('user.id')) + user=relationship(User) + +engine = create_engine('sqlite:///secretdiary.db') +Base.metadata.create_all(engine) + diff --git a/src/service/secretdiary.db b/src/service/secretdiary.db new file mode 100644 index 0000000000000000000000000000000000000000..4badb7f6f3ba541f6b8073322cc66109fb3e2e4a GIT binary patch literal 4096 zcmeH|!D_-l5QY;YEe3j&Tn9=a0R^q4ryd&Ps=;()S6k{yVzbsj)M6sF$4Vcn574LS zt#8n5FxE)%&c;p%6(K8#qHql$2!a$@HnL=FKZ{9X zhnIxn_s2<8Ac>!Xbd~vv93OiousoHH6-5!>&q8P5Q`d85ukn;M2-3RvhI?;ZqG1<+?-I9Im` zG8>rHt1CGT2&yB3uz@T2-dy~s?0-V6%5|CMIo45Sow#qx>1UP{`6X5s%o`G^X JPT(IA_yHw%td#%& literal 0 HcmV?d00001 From 9331f87d28b6d34500cc7c1c86077ce9eaca3560 Mon Sep 17 00:00:00 2001 From: Shin Date: Thu, 22 Feb 2018 16:30:49 +0000 Subject: [PATCH 02/54] fill up team member --- src/service/team_members.txt | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/service/team_members.txt b/src/service/team_members.txt index 50bdea8..88fbce5 100644 --- a/src/service/team_members.txt +++ b/src/service/team_members.txt @@ -1,3 +1,4 @@ -Jeremy Heng -John Galt -Audrey Shida +Wei Ran +Liu Chao +Kong Chao +Bai Xin From e9e4cee9f1cf89fed113d3b2a4db4207795a655e Mon Sep 17 00:00:00 2001 From: Shin Date: Thu, 22 Feb 2018 16:31:06 +0000 Subject: [PATCH 03/54] add token table --- src/service/model.py | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/src/service/model.py b/src/service/model.py index 61bb53c..191c71d 100644 --- a/src/service/model.py +++ b/src/service/model.py @@ -7,33 +7,51 @@ from passlib.apps import custom_app_context as pwd_context Base = declarative_base() +secret_key = ''.join(random.choice(string.ascii_uppercase+string.digits) for x in xrange(32)) class User(Base): __tablename__='user' id=Column(Integer,primary_key=True) username=Column(String(32),index=True,nullable=False) - password_hash=Column(String(64)) - fullname=Column(String(32),nullable=False) - age=Column(Integer) + password_hash=Column(String(64),nullable=False) + fullname=Column(String(100),nullable=False) + age=Column(Integer, nullable=False) def hash_password(self,password): self.password_hash=pwd_context.encrypt(password) def verify_password(self,password): return pwd_context.verify(password,self.password_hash) + class Diary(Base): __tablename__='diary' id=Column(Integer,primary_key=True) title=Column(String(100),nullable=False) + author=Column(String(32),ForeignKey('user.username'),index=True) publish_date=Column(Date,nullable=False) public = Column(Boolean,nullable=False) text=Column(String,nullable=False) - - user_id=Column(Integer,ForeignKey('user.id')) user=relationship(User) + + @property + def serialize(self): + return { + 'id':self.id, + 'title':self.title, + 'author': self.author, + 'publish_date':self.publish_date, + 'public': self.public, + 'text': self.text + } + +class Token(Base): + __tablename__='token' + id = Column(Integer,primary_key=True) + uuid=Column(String, index=True,nullable=False) + expired=Column(Boolean,nullable=False) engine = create_engine('sqlite:///secretdiary.db') Base.metadata.create_all(engine) From f4e6fd76fee67526a1de585d297ebb42c6340914 Mon Sep 17 00:00:00 2001 From: Shin Date: Thu, 22 Feb 2018 16:31:42 +0000 Subject: [PATCH 04/54] First draft of REST api, further test required --- src/service/app.py | 176 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 174 insertions(+), 2 deletions(-) diff --git a/src/service/app.py b/src/service/app.py index ade6772..cd45c08 100644 --- a/src/service/app.py +++ b/src/service/app.py @@ -1,9 +1,27 @@ #!/usr/bin/python -from flask import Flask +from flask import Flask, request,jsonify, abort, g +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker from flask_cors import CORS import json import os +from models import Base, User, Diary, Token +import uuid +from flask_httpauth import HTTPBasicAuth +from datetime import date + +auth = HTTPBasicAuth() + +# Build database connection +engine = create_engine('sqlite"///secretDiary,db') +Base.metadata.bind=engine +DBSession = sessionmaker(bind=enigne) +session = DBSession() + +# clear up token table at every start +session.query(token).delete() +session.commit() app = Flask(__name__) # Enable cross origin sharing for all endpoints @@ -12,6 +30,159 @@ # Remember to update this list ENDPOINT_LIST = ['/', '/meta/heartbeat', '/meta/members'] + +@auth.verify_password +def verify_password(username,password): + user = session.query(User).filter_by(username=username).first() + if not user or not user.verify_password(password): + return Fasle + g.user=user + return True + +@app.route("/users/register",['POST']) +def user_registration(): + if request.method == 'POST': + username=request.json.get('username') + password=request.json.get('password') + fullname=request.json.get('fullname') + age=request.json.get('age') + + if username is None or password is None or fullname is None: + print 'missing required field' + abort(400) + + if session.query(User).filter_by(username=username).first() is not None: + err = 'user already exist' + return jsonify({'status':False,'error':'User already exists!'}),200# + user = User(username=username, fullname=fullname,age=age) + user.hash_password(password) + session.add(user) + session.commit() + + return jsonify({'status':True}),201# + +@auth.login_required +def get_token(): + temp_uuid = str(uuid.uuid4()) + newToken = Token(uuid=temp_uuid,expired=False) + session.add(newToken) + session.commit() + return jsonify({'status':True, 'token':temp_uuid}), 200# + +@app.route('/users/authenticate',['POST']) +def get_authentication(): + if request.method=='POST': + username = request.json.get('username') + password = request.json.get('password') + if verify_password(username,password): + get_token() + else: + return jsonify({'status': False}), 200# + +@app.route('/users/expire',['POST']) +def expire_token(): + if request.method=='POST': + try: + temp_uuid = request.json.get('token') + target = session.query(token).filter_by(uuid=temp_uuid).first() + target.expired=True + session.add(target) + session.commit() + return jsonify({'status':True}),200# + except: + return jsonify({'status':False}),200# + +@app.route('/users',['POST']) +@auth.login_required +def get_user(): + if request.method='POST': + curr_uuid = request.json.get('token') + target = session.query(Token).filter_by(uuid = curr_uuid).first() + if target.expired: + return jsonify({'status': False,'Invalid authentication token.'}),200# + else: + username = g.user.username + curr_user = session.query(User).filter_by(username=username).first() + return jsonify({'status':True, 'username':username, 'fullname': curr_user.fullname, 'age': curr_user.age}),200# + + +@auth.login_required +def get_secret_diary(): + curr_token = request.json.get('token') + target = session.query(Token).filter_by(uuid=curr_token).first() + if not target.expire: + diaryList = session.query(Diary).filter_by(username=g.user.username) + if len(diaryList): + diaryList_serialized = [d.serialize() for d in diaryList] + return jsonify({'status': True, 'result':diaryList_serialized}), 201# + else: + return jsonify({'status': True, 'result':[]}), 201# + return jsonify({'status': False, 'error': 'Invalid authentication token.'}), 200# + + +@app.route('/diary', method=['GET','POST']) +def get_diary(): + if request.method == 'GET': + diaryList = session.query(Diary).filter_by(public=True) + if len(diaryList): + diaryList_serialized = [d.serialize() for d in diaryList] + return jsonify({'status': True,'result':diaryList_serialized }),201# + else: + return jsonify({'status': True, 'result': []}),201# + else: + get_secret_diary() + + +@app.route('/diary/create',['POST']) +@auth.login_required +def create_diary(): + if request.method == 'POST': + curr_token = request.json.get('token') + target= session.query(Token).filter_by(uuid=curr_token).first() + + if not target.expire: + title = request.json.get('title') + public = request.json.get('public') + text = request.json.get('text') + newDiary = Diary(title=title,public=public,text=text,author=g.user.username,publish_date=date.today().isoformat()) + session.add(newDiary) + session.commit() + return jsonify({'status': True}), 201# + else: + return jsonify({'status':False, 'error':'Invalid authentication token.'}), 200# + +@app.route('/diary/delete',['POST']) +@auth.login_required +def delete_diary(): + if request.mthod='POST': + curr_token = request.json.get('token') + target= session.query(Token).filter_by(uuid=curr_token).first() + if not target.expire: + curr_id = request.json.get('id') + d = session.query(Diary).filter_by(id=id).first() + session.delete(d) + session.commit() + return jsonify({'status': True}), 200# + else: + return jsonify({'status':False, 'error':'Invalid authentication token.'}), 200# + +@app.route('/diary/permission',['POST']) +@auth.login_required +def change_permission(): + if request.method='POST': + curr_token = request.json.get('token') + target = session.query(Token).filter_by(uuid=curr_token).first() + if not target.expire: + public = request.json.get('public') + id = request.json.get('id') + d = session.query(Diary).filter_by(id=id).first() + d.permission=public + session.add(d) + session.commit() + return jsonify({'status':True}), 200# + else: + return jsonify({'status':False, 'error':'Invalid authentication token.'}), 200# + def make_json_response(data, status=True, code=200): """Utility function to create the JSON responses.""" @@ -51,6 +222,7 @@ def meta_members(): return make_json_response(team_members) + if __name__ == '__main__': # Change the working directory to the script directory abspath = os.path.abspath(__file__) @@ -58,4 +230,4 @@ def meta_members(): os.chdir(dname) # Run the application - app.run(debug=False, port=8080, host="0.0.0.0") + app.run(debug=True, port=8080, host="0.0.0.0") From b1b6df25419997691a7640c1173ae8025e27a401 Mon Sep 17 00:00:00 2001 From: Shin Date: Thu, 22 Feb 2018 16:35:50 +0000 Subject: [PATCH 05/54] update database file --- src/service/model.py | 1 - src/service/secretdiary.db | Bin 4096 -> 6144 bytes 2 files changed, 1 deletion(-) diff --git a/src/service/model.py b/src/service/model.py index 191c71d..e226226 100644 --- a/src/service/model.py +++ b/src/service/model.py @@ -7,7 +7,6 @@ from passlib.apps import custom_app_context as pwd_context Base = declarative_base() -secret_key = ''.join(random.choice(string.ascii_uppercase+string.digits) for x in xrange(32)) class User(Base): __tablename__='user' diff --git a/src/service/secretdiary.db b/src/service/secretdiary.db index 4badb7f6f3ba541f6b8073322cc66109fb3e2e4a..e44f1914aebe0f602834b0302fe5d12da7268608 100644 GIT binary patch delta 272 zcmZorXfT){Ey&8iz`zE?Fu*!d$5@<|LHFYhUZ4;w!+8c~8>Ux`M;Ij;&QENNtoLAL z6IT~!Ow7znNv+7Nh%d>{PR)xiEzL{;v)G)2TpdGP6+Hc1Tq6`vUx`M>Y$x1Tk(t!f3+> E0Q!gul>h($ From cf48b35b0bcc8e7f2ca1beeeaacfac381e6d4195 Mon Sep 17 00:00:00 2001 From: Shin Date: Fri, 23 Feb 2018 04:07:27 +0000 Subject: [PATCH 06/54] Remove redundant column --- src/service/models.py | 57 ++++++++++++++++++++++++++++++++++++++ src/service/secretDiary.db | 0 2 files changed, 57 insertions(+) create mode 100644 src/service/models.py create mode 100644 src/service/secretDiary.db diff --git a/src/service/models.py b/src/service/models.py new file mode 100644 index 0000000..e226226 --- /dev/null +++ b/src/service/models.py @@ -0,0 +1,57 @@ +import os +import sys +from sqlalchemy import Column, ForeignKey, Integer, String, Date,Boolean +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import relationship +from sqlalchemy import create_engine +from passlib.apps import custom_app_context as pwd_context + +Base = declarative_base() + +class User(Base): + __tablename__='user' + + id=Column(Integer,primary_key=True) + username=Column(String(32),index=True,nullable=False) + password_hash=Column(String(64),nullable=False) + fullname=Column(String(100),nullable=False) + age=Column(Integer, nullable=False) + + def hash_password(self,password): + self.password_hash=pwd_context.encrypt(password) + + def verify_password(self,password): + return pwd_context.verify(password,self.password_hash) + + +class Diary(Base): + __tablename__='diary' + + id=Column(Integer,primary_key=True) + title=Column(String(100),nullable=False) + author=Column(String(32),ForeignKey('user.username'),index=True) + publish_date=Column(Date,nullable=False) + public = Column(Boolean,nullable=False) + text=Column(String,nullable=False) + user=relationship(User) + + @property + def serialize(self): + return { + 'id':self.id, + 'title':self.title, + 'author': self.author, + 'publish_date':self.publish_date, + 'public': self.public, + 'text': self.text + } + +class Token(Base): + __tablename__='token' + id = Column(Integer,primary_key=True) + uuid=Column(String, index=True,nullable=False) + expired=Column(Boolean,nullable=False) + +engine = create_engine('sqlite:///secretdiary.db') +Base.metadata.create_all(engine) + diff --git a/src/service/secretDiary.db b/src/service/secretDiary.db new file mode 100644 index 0000000..e69de29 From af7d997c51f8be3d1071651c8d919c9bd7582a63 Mon Sep 17 00:00:00 2001 From: Shin Date: Fri, 23 Feb 2018 04:08:00 +0000 Subject: [PATCH 07/54] fix minor syntax error --- src/service/app.py | 31 ++++++++++------------ src/service/model.py | 57 ----------------------------------------- src/service/models.pyc | Bin 0 -> 2895 bytes 3 files changed, 14 insertions(+), 74 deletions(-) delete mode 100644 src/service/model.py create mode 100644 src/service/models.pyc diff --git a/src/service/app.py b/src/service/app.py index cd45c08..6a3378e 100644 --- a/src/service/app.py +++ b/src/service/app.py @@ -14,14 +14,11 @@ auth = HTTPBasicAuth() # Build database connection -engine = create_engine('sqlite"///secretDiary,db') +engine = create_engine('sqlite:///secretDiary.db') Base.metadata.bind=engine -DBSession = sessionmaker(bind=enigne) +DBSession = sessionmaker(bind=engine) session = DBSession() -# clear up token table at every start -session.query(token).delete() -session.commit() app = Flask(__name__) # Enable cross origin sharing for all endpoints @@ -39,7 +36,7 @@ def verify_password(username,password): g.user=user return True -@app.route("/users/register",['POST']) +@app.route("/users/register",methods=['POST']) def user_registration(): if request.method == 'POST': username=request.json.get('username') @@ -69,7 +66,7 @@ def get_token(): session.commit() return jsonify({'status':True, 'token':temp_uuid}), 200# -@app.route('/users/authenticate',['POST']) +@app.route('/users/authenticate',methods=['POST']) def get_authentication(): if request.method=='POST': username = request.json.get('username') @@ -79,7 +76,7 @@ def get_authentication(): else: return jsonify({'status': False}), 200# -@app.route('/users/expire',['POST']) +@app.route('/users/expire',methods=['POST']) def expire_token(): if request.method=='POST': try: @@ -92,14 +89,14 @@ def expire_token(): except: return jsonify({'status':False}),200# -@app.route('/users',['POST']) +@app.route('/users',methods=['POST']) @auth.login_required def get_user(): - if request.method='POST': + if request.method == 'POST': curr_uuid = request.json.get('token') target = session.query(Token).filter_by(uuid = curr_uuid).first() if target.expired: - return jsonify({'status': False,'Invalid authentication token.'}),200# + return jsonify({'status': False,'error':'Invalid authentication token.'}),200# else: username = g.user.username curr_user = session.query(User).filter_by(username=username).first() @@ -120,7 +117,7 @@ def get_secret_diary(): return jsonify({'status': False, 'error': 'Invalid authentication token.'}), 200# -@app.route('/diary', method=['GET','POST']) +@app.route('/diary', methods=['GET','POST']) def get_diary(): if request.method == 'GET': diaryList = session.query(Diary).filter_by(public=True) @@ -133,7 +130,7 @@ def get_diary(): get_secret_diary() -@app.route('/diary/create',['POST']) +@app.route('/diary/create',methods=['POST']) @auth.login_required def create_diary(): if request.method == 'POST': @@ -151,10 +148,10 @@ def create_diary(): else: return jsonify({'status':False, 'error':'Invalid authentication token.'}), 200# -@app.route('/diary/delete',['POST']) +@app.route('/diary/delete',methods=['POST']) @auth.login_required def delete_diary(): - if request.mthod='POST': + if request.method=='POST': curr_token = request.json.get('token') target= session.query(Token).filter_by(uuid=curr_token).first() if not target.expire: @@ -166,10 +163,10 @@ def delete_diary(): else: return jsonify({'status':False, 'error':'Invalid authentication token.'}), 200# -@app.route('/diary/permission',['POST']) +@app.route('/diary/permission',methods=['POST']) @auth.login_required def change_permission(): - if request.method='POST': + if request.method=='POST': curr_token = request.json.get('token') target = session.query(Token).filter_by(uuid=curr_token).first() if not target.expire: diff --git a/src/service/model.py b/src/service/model.py deleted file mode 100644 index e226226..0000000 --- a/src/service/model.py +++ /dev/null @@ -1,57 +0,0 @@ -import os -import sys -from sqlalchemy import Column, ForeignKey, Integer, String, Date,Boolean -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import relationship -from sqlalchemy import create_engine -from passlib.apps import custom_app_context as pwd_context - -Base = declarative_base() - -class User(Base): - __tablename__='user' - - id=Column(Integer,primary_key=True) - username=Column(String(32),index=True,nullable=False) - password_hash=Column(String(64),nullable=False) - fullname=Column(String(100),nullable=False) - age=Column(Integer, nullable=False) - - def hash_password(self,password): - self.password_hash=pwd_context.encrypt(password) - - def verify_password(self,password): - return pwd_context.verify(password,self.password_hash) - - -class Diary(Base): - __tablename__='diary' - - id=Column(Integer,primary_key=True) - title=Column(String(100),nullable=False) - author=Column(String(32),ForeignKey('user.username'),index=True) - publish_date=Column(Date,nullable=False) - public = Column(Boolean,nullable=False) - text=Column(String,nullable=False) - user=relationship(User) - - @property - def serialize(self): - return { - 'id':self.id, - 'title':self.title, - 'author': self.author, - 'publish_date':self.publish_date, - 'public': self.public, - 'text': self.text - } - -class Token(Base): - __tablename__='token' - id = Column(Integer,primary_key=True) - uuid=Column(String, index=True,nullable=False) - expired=Column(Boolean,nullable=False) - -engine = create_engine('sqlite:///secretdiary.db') -Base.metadata.create_all(engine) - diff --git a/src/service/models.pyc b/src/service/models.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ec9ed5c771b066ceb509eeb9e5adcb3d33a3c00 GIT binary patch literal 2895 zcmcImO>f&q5FJvoY|E14II-h?pm4v{LnH)2b13>@*g=4{Kn`?zC@%ypu5CJ`sB%|M zROFVPd+5*TzYF>U+V^H9I=MA~Lwd)vv#Z^mnfGSd`lsLh?$w|1SQbwU{}0gYD~Jq# zffOQfqX!ZPY7eCdrEE#ulCmvvTgnxQSETGn+>vrs;#DcvBwmw%tF)w8m$EBy*Z12} zY)ILYxaa#Tx>{f2zVCOW*p%{y#9I=WuDrw%Zc4T)=BAut|26qTX#6$amTY}#?Kak1 zl5H%ly~cW5Okc9Tyo3`w9KP6v?CN}S=GrhnOr6p3!>TGwIvE5ox-E#zjEl5RU4ChjlhhhN z(!)q?3Ye>jJ$yq*GOx~t>W?fY#>2#WmE1coE(|v!jrfw3+lOLkl zzaR|ar)i5rF)cA|=GCmg?*Q4NWmU3}VL+x}&)Q)F_ zQ){19b(Wl`_I$t%^q|%hr+Sj*_y8lK!u|klbY7KabeW#j>BNnWj=#Qt|K6xJ*4<5~ z`Q6N1nxdMP24l7!kKpxXJ~pGW%1mL0)46WV9h2qyx3Q?@_7XI%(gAh#7L>+S_<4c! zg>U#7-QX1B;L_Cj={&j#Ro#gQqKGS8vkTnOZ`L?*2d0G+13eIPnIx06G)bbQN)p6i zRV8jwZa9MJ_6LiAu;GJ}QaC@%f$%X#_2KCc(d^$4Z^u!xGq_@Bn`lR& z%sfrOX((Y3dpd%GAf^9FUkSSTn&rll%FUcD7DuzqHRD@iZZ8%|EIw*O@mld3 z3ROoQ91lp~$I%CndMcN@!YJ_5nLDp)#{*7hCq)i&Wh~Alg&M}nY*tXM_qs;(2}Yw& zDL$k4oZ<@zts%;tEAU(k^H~cKt2{08-wk)N45Wmupxe9yf;J+XqCJZDD9}7RqW7sW z0?Lc%Lu%>=qwSq(Q&W$KyDPUMhEK5@5xl;{)zuVbc^-WU%aym+N0oi7%i~&>B2SgQ z;NxIh-(IMBd{R9{S;n|N%$btqCn*1uEWFAVs9s)W;7Eh>4T70r@vz}`3g(DdRWJ_- zowtg*ztd(YP>iyE2AJp5yf)dp2;*1S;~tt_gFqM&zP-Q_AojN+cjlYX2saHrBb-uo zn4Jtbs5P{*S{3cwY8l24(qepW%DIP?0w=^|k0?ctxe8c($Mkf>9b4olLwv*7i1_!n6?ZwrhmnWlKJ9c-3G2Ut6rL#PDTtiv!51G%X;Hj` h2 Date: Fri, 23 Feb 2018 07:22:47 +0000 Subject: [PATCH 08/54] clear up databse --- src/service/secretdiary.db | Bin 6144 -> 6144 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/src/service/secretdiary.db b/src/service/secretdiary.db index e44f1914aebe0f602834b0302fe5d12da7268608..1bf422db1e7a4cc415ba8305fe7cf0b36c5a1ebc 100644 GIT binary patch delta 482 zcma*j%Sr-a90l-i<}av0L{N*cMc{z882!eXZ!U`#-ZCmJWhTs(jx*}eG?VwsCVPW= zfe30TNcb+%q6hF1TBd~5(*1$oIcJQ=_%T5FpZ1fK|GoSMJ{kyuXCSj}&mr8`X)g*s zgaTB*VRg(}w{5u&LztG^b&U2A;R(i=>GpCNGnKTj>nCC)nbDXI7qNT!oMzbd^r>1; z2+>uUH2I%h@SYUbMS}+70VZD6R-Qr4@?D>9*bK zTaAJ0GQ)UYzA5RWsuPdd7lxf32${GQRh!Xfx;RoxX7E86qn+PKeGMlET-1D@_qh;d7z9LOu){ NwT?lDK=ZFd`~XpYf%^ae delta 45 tcmZoLXfT){&B!`Y#+i|IW5N>V%`7~Bm>Ib?Gx9LAEN0 Date: Fri, 23 Feb 2018 07:24:49 +0000 Subject: [PATCH 09/54] remove old databse --- src/service/secretDiary.db | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 src/service/secretDiary.db diff --git a/src/service/secretDiary.db b/src/service/secretDiary.db deleted file mode 100644 index e69de29..0000000 From 3e8190c9a155072ae271f9fbec54a19423d7d902 Mon Sep 17 00:00:00 2001 From: Shin Date: Fri, 23 Feb 2018 10:56:49 +0000 Subject: [PATCH 10/54] models.py --- src/service/models.pyc | Bin 2895 -> 2849 bytes src/service/secretdiary.db | Bin 6144 -> 6144 bytes 2 files changed, 0 insertions(+), 0 deletions(-) diff --git a/src/service/models.pyc b/src/service/models.pyc index 8ec9ed5c771b066ceb509eeb9e5adcb3d33a3c00..e62f86a0cac5f19699a7312b114fe231ee5d421d 100644 GIT binary patch delta 334 zcmX>vwor_n`7AB8l*UMc9!<_!&|K7*bdnS{Q(aFhmJ51O;obO*Us!6i#LY+5*DNKA|F5y~J!1xS=|0*TDx{IvX{ z+{BW}%IpP_AmL&@Ai==I%*X|X0zgtjX!06%v&qldWra#OfRY78`30#(C6z%MK+fcI zT*0zI3P6?=5Elyo2{uMHCLu-%AQS?@&C@wF8CkV}68e*ma^7Rqn!JQ-2|K@-s2Cd$ FBLF5=IR^j$ delta 390 zcmYk0u}T9$5QhIra=USJr}1Krh=qxYCKiHCIw1&lRvWNL7uYQ#sNpUu0l`8GE1MO> zPQl7fd1_g zAs7M6qCkTRY!NnuVU~GBgD7|AXPkxHkuy#eb`duAUkz%oOE40*$lE$}zg_0ci4QlU zVLH_ztC2wy(DPohKo&91Gn?*soDNT{j$BXFsppQwcFmN~y#kI){^DE(?nxXr1aIjT zk2Q~Vj}3;a$no+fi_9mWP$czV?ZiFEE|L3`t(KNN*2<&8nD|r2>Dkz(ld0a~#yzY4 rs&2CKFj=ep+oJ&CZ?_(;v_JZ zc45R^x<<;%+Jzs1DzQ{uD*gZhv2`Q~e}Lf}=?u?#-uGBKmOkb&8!uIP7KwkpE+B*w z=o&!_SSpE&=$df!E2^F#KdE~-NwOgGO*+Nra`==TShnvBBd0%`1Zjf1D407$q!)32fUnRR!=BM@jQ=D+vEc8bJlRs4g122jYf5Aqp?y_$P#rx z&TyW5p*WgZ-J;^}%NXL{Yj^ORJ1Ne+gYeJ^=8GaF95b`z7%mZ9o^$DMpsrvVwbH8G z>68_{EZTBe5!H$%iMk~_qSbLLx~y56t7^=gyh3m_B`-iNKr8b<+``m`VS-=+lPP%y zdWlM*LhgRL76sHb?3 ocQ(!Hrm}0-y`$Hzq1l!vyz_#^f9-A%+?;dSUyx2gE;CE?7nMwh761SM delta 684 zcma)%%Wo246ve;qyC4s3+NL0yKAfbOLhQf{!!VHOg2F&+Erk(GAtuUn2AFgNDNG-% zTH?-4arTXg+a_If;~(I@JL95>OB)jt-MLc+HF4R+y^DKK&N;sW=72ex#;(Ck%I8A# zkN0B;Av-!paG!j|AMkB-J~%9sWxF{Bv-p~M4;F9P96p~9_ru+)tgGGDmf9RGyV-() zyFU-3_p7_+1bJ${CepakQMaFI3bm3eidj)IzhjU2jm)r%l-reAm&BE9j#?GVfxo&S zC5ahP5_2i>F=gGTfTjf9!8{p!zJp=#i}fY3!{_zlzB;O4X{;e;7T27XYt7Jga~IE= z7x?-x?&b}PiU5z`82GbETM)E5aiICbg=xIo(7I~P=xD8`pZ9OKjHc3gz;isqFn(hv zmsQg#yYT&(YJTC#$K`I-%l3eTNSyt*-S?Cbwyv>i)NErxY!Q2#f@IE zqOLt@6%w)4rC$7>k$c2&iQp$(o=ti#U~U}d|F2IR;B|ExTGOIMwxQ+=434JWOxT5DqRy8o{lnnf|gY-K{HA@3Cqoabt(Xt>jG|S68FLR2J;A(%`ogz4ePs5aVPzXQ?UnPSqK*@ELh~KT9y8QqE From 45ead1d1c75dc379abbf115486e1a524ed37b5b7 Mon Sep 17 00:00:00 2001 From: Shin Date: Fri, 23 Feb 2018 10:57:42 +0000 Subject: [PATCH 11/54] optimize model --- src/service/models.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/service/models.py b/src/service/models.py index e226226..476b6ee 100644 --- a/src/service/models.py +++ b/src/service/models.py @@ -23,17 +23,15 @@ def hash_password(self,password): def verify_password(self,password): return pwd_context.verify(password,self.password_hash) - class Diary(Base): __tablename__='diary' id=Column(Integer,primary_key=True) title=Column(String(100),nullable=False) - author=Column(String(32),ForeignKey('user.username'),index=True) + author=Column(String(32),nullable=False) publish_date=Column(Date,nullable=False) public = Column(Boolean,nullable=False) text=Column(String,nullable=False) - user=relationship(User) @property def serialize(self): @@ -41,7 +39,7 @@ def serialize(self): 'id':self.id, 'title':self.title, 'author': self.author, - 'publish_date':self.publish_date, + 'publish_date':self.publish_date.isoformat(), 'public': self.public, 'text': self.text } From 18e0e86b61bc9d9461d706172f4b6835eb1dac90 Mon Sep 17 00:00:00 2001 From: Shin Date: Fri, 23 Feb 2018 10:58:08 +0000 Subject: [PATCH 12/54] fix typos and handle exceptions --- src/service/app.py | 69 ++++++++++++++++++++++++---------------------- 1 file changed, 36 insertions(+), 33 deletions(-) diff --git a/src/service/app.py b/src/service/app.py index 6a3378e..5eb9f82 100644 --- a/src/service/app.py +++ b/src/service/app.py @@ -14,7 +14,7 @@ auth = HTTPBasicAuth() # Build database connection -engine = create_engine('sqlite:///secretDiary.db') +engine = create_engine('sqlite:///secretdiary.db') Base.metadata.bind=engine DBSession = sessionmaker(bind=engine) session = DBSession() @@ -25,19 +25,20 @@ CORS(app) # Remember to update this list -ENDPOINT_LIST = ['/', '/meta/heartbeat', '/meta/members'] +ENDPOINT_LIST = ['/', '/meta/heartbeat', '/meta/members','/users/register'] @auth.verify_password def verify_password(username,password): user = session.query(User).filter_by(username=username).first() if not user or not user.verify_password(password): - return Fasle + return False g.user=user return True @app.route("/users/register",methods=['POST']) def user_registration(): + print request.json if request.method == 'POST': username=request.json.get('username') password=request.json.get('password') @@ -49,7 +50,6 @@ def user_registration(): abort(400) if session.query(User).filter_by(username=username).first() is not None: - err = 'user already exist' return jsonify({'status':False,'error':'User already exists!'}),200# user = User(username=username, fullname=fullname,age=age) user.hash_password(password) @@ -58,7 +58,6 @@ def user_registration(): return jsonify({'status':True}),201# -@auth.login_required def get_token(): temp_uuid = str(uuid.uuid4()) newToken = Token(uuid=temp_uuid,expired=False) @@ -68,24 +67,26 @@ def get_token(): @app.route('/users/authenticate',methods=['POST']) def get_authentication(): - if request.method=='POST': - username = request.json.get('username') - password = request.json.get('password') - if verify_password(username,password): - get_token() - else: - return jsonify({'status': False}), 200# + username = request.json.get('username') + password = request.json.get('password') + if verify_password(username,password): + return get_token() + else: + return jsonify({'status': False}), 200# @app.route('/users/expire',methods=['POST']) def expire_token(): if request.method=='POST': try: temp_uuid = request.json.get('token') - target = session.query(token).filter_by(uuid=temp_uuid).first() - target.expired=True - session.add(target) - session.commit() - return jsonify({'status':True}),200# + target = session.query(Token).filter_by(uuid=temp_uuid).first() + if target: + target.expired=True + session.add(target) + session.commit() + return jsonify({'status':True}),200# + else: + return jsonify({'status':False}),200# except: return jsonify({'status':False}),200# @@ -95,7 +96,7 @@ def get_user(): if request.method == 'POST': curr_uuid = request.json.get('token') target = session.query(Token).filter_by(uuid = curr_uuid).first() - if target.expired: + if (not target) or target.expired: return jsonify({'status': False,'error':'Invalid authentication token.'}),200# else: username = g.user.username @@ -107,10 +108,11 @@ def get_user(): def get_secret_diary(): curr_token = request.json.get('token') target = session.query(Token).filter_by(uuid=curr_token).first() - if not target.expire: - diaryList = session.query(Diary).filter_by(username=g.user.username) - if len(diaryList): - diaryList_serialized = [d.serialize() for d in diaryList] + if target and not target.expired: + diaryList = session.query(Diary).filter_by(author=g.user.username) + if diaryList.first(): + print diaryList + diaryList_serialized = [d.serialize for d in diaryList.all()] return jsonify({'status': True, 'result':diaryList_serialized}), 201# else: return jsonify({'status': True, 'result':[]}), 201# @@ -121,13 +123,14 @@ def get_secret_diary(): def get_diary(): if request.method == 'GET': diaryList = session.query(Diary).filter_by(public=True) - if len(diaryList): - diaryList_serialized = [d.serialize() for d in diaryList] - return jsonify({'status': True,'result':diaryList_serialized }),201# + if diaryList.first(): + diaryList_serialized = [d.serialize for d in diaryList.all()] + + return jsonify({'status': True,'result':diaryList_serialized }),200# else: - return jsonify({'status': True, 'result': []}),201# + return jsonify({'status': True, 'result': []}),200# else: - get_secret_diary() + return get_secret_diary() @app.route('/diary/create',methods=['POST']) @@ -137,11 +140,11 @@ def create_diary(): curr_token = request.json.get('token') target= session.query(Token).filter_by(uuid=curr_token).first() - if not target.expire: + if target and not target.expired: title = request.json.get('title') public = request.json.get('public') text = request.json.get('text') - newDiary = Diary(title=title,public=public,text=text,author=g.user.username,publish_date=date.today().isoformat()) + newDiary = Diary(title=title,author=g.user.username,publish_date=date.today(),public=public,text=text) session.add(newDiary) session.commit() return jsonify({'status': True}), 201# @@ -154,9 +157,9 @@ def delete_diary(): if request.method=='POST': curr_token = request.json.get('token') target= session.query(Token).filter_by(uuid=curr_token).first() - if not target.expire: + if target and not target.expired: curr_id = request.json.get('id') - d = session.query(Diary).filter_by(id=id).first() + d = session.query(Diary).filter_by(id=curr_id).first() session.delete(d) session.commit() return jsonify({'status': True}), 200# @@ -169,11 +172,11 @@ def change_permission(): if request.method=='POST': curr_token = request.json.get('token') target = session.query(Token).filter_by(uuid=curr_token).first() - if not target.expire: + if target and not target.expired: public = request.json.get('public') id = request.json.get('id') d = session.query(Diary).filter_by(id=id).first() - d.permission=public + d.public=public session.add(d) session.commit() return jsonify({'status':True}), 200# From 61448de65448be153c7886300226725974e16bfb Mon Sep 17 00:00:00 2001 From: Shin Date: Fri, 23 Feb 2018 11:35:47 +0000 Subject: [PATCH 13/54] add username column in token table to realize no Auth --- src/service/models.py | 2 ++ src/service/models.pyc | Bin 2849 -> 2940 bytes src/service/secretdiary.db | Bin 6144 -> 6144 bytes 3 files changed, 2 insertions(+) diff --git a/src/service/models.py b/src/service/models.py index 476b6ee..067568e 100644 --- a/src/service/models.py +++ b/src/service/models.py @@ -49,6 +49,8 @@ class Token(Base): id = Column(Integer,primary_key=True) uuid=Column(String, index=True,nullable=False) expired=Column(Boolean,nullable=False) + username=Column(String(32),ForeignKey('user.username')) + user=relationship(User) engine = create_engine('sqlite:///secretdiary.db') Base.metadata.create_all(engine) diff --git a/src/service/models.pyc b/src/service/models.pyc index e62f86a0cac5f19699a7312b114fe231ee5d421d..c42db4a4c4440ed3d8cf04e7475f5d9ab75f2bb7 100644 GIT binary patch delta 191 zcmZ1|_D773`7#i>PlAR;d@ zH&sJ$@)r&-$sk6cM35|qUDIH`q3iLJ(%2?9O;l zf)V17WUy39W@1q#m|&W$!1S7jmw|zSk@*Y*^BLwvn*~`8FpC;7u`{TODst!-XJqE7 z7b|4sCnZ%*-p((-Nnj7NOxv6)i;pQL094uTA8!s|2U)(InahzFSmywkrlta|g x&@$D`G|@me**wim*CZu1RX54Nz+BfLInBT#*(}j4#UvHvqD>rkm{o{T3;=dCdanQg delta 399 zcmZoLXfT+N#dDW|Ih2{3iH%X8;qGKXmUN{6RyJ{6QO4ZNyp+_6%!>HZ;?yEAk(Zd8 z3gWO${=#S^#=^X8`5%)QBglX=BXDe6sIN^rIt*7 z$S%(UbdDA<#MCx%>|wSk3J=Op$`1%mF7VUy$@g|q@zDznGz)SoE-gqg%MSN0^DPXB h@U-+SD=^A5_jmPkb~Or43dqdOO7k(>{DYf=1pxWmbJG9- From 59a20ae59dc7f7ba691f904209a26c3c8a407bea Mon Sep 17 00:00:00 2001 From: Shin Date: Fri, 23 Feb 2018 11:36:55 +0000 Subject: [PATCH 14/54] basic tests finished on a token-domainted api server --- src/service/app.py | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/src/service/app.py b/src/service/app.py index 5eb9f82..521eb3e 100644 --- a/src/service/app.py +++ b/src/service/app.py @@ -58,9 +58,9 @@ def user_registration(): return jsonify({'status':True}),201# -def get_token(): +def get_token(username): temp_uuid = str(uuid.uuid4()) - newToken = Token(uuid=temp_uuid,expired=False) + newToken = Token(uuid=temp_uuid,expired=False,username=username) session.add(newToken) session.commit() return jsonify({'status':True, 'token':temp_uuid}), 200# @@ -70,7 +70,7 @@ def get_authentication(): username = request.json.get('username') password = request.json.get('password') if verify_password(username,password): - return get_token() + return get_token(username) else: return jsonify({'status': False}), 200# @@ -91,7 +91,7 @@ def expire_token(): return jsonify({'status':False}),200# @app.route('/users',methods=['POST']) -@auth.login_required +#@auth.login_required def get_user(): if request.method == 'POST': curr_uuid = request.json.get('token') @@ -99,19 +99,17 @@ def get_user(): if (not target) or target.expired: return jsonify({'status': False,'error':'Invalid authentication token.'}),200# else: - username = g.user.username + username =target.username curr_user = session.query(User).filter_by(username=username).first() return jsonify({'status':True, 'username':username, 'fullname': curr_user.fullname, 'age': curr_user.age}),200# - -@auth.login_required +#@auth.login_required def get_secret_diary(): curr_token = request.json.get('token') target = session.query(Token).filter_by(uuid=curr_token).first() if target and not target.expired: - diaryList = session.query(Diary).filter_by(author=g.user.username) + diaryList = session.query(Diary).filter_by(author=target.username) if diaryList.first(): - print diaryList diaryList_serialized = [d.serialize for d in diaryList.all()] return jsonify({'status': True, 'result':diaryList_serialized}), 201# else: @@ -134,7 +132,7 @@ def get_diary(): @app.route('/diary/create',methods=['POST']) -@auth.login_required +#@auth.login_required def create_diary(): if request.method == 'POST': curr_token = request.json.get('token') @@ -144,7 +142,7 @@ def create_diary(): title = request.json.get('title') public = request.json.get('public') text = request.json.get('text') - newDiary = Diary(title=title,author=g.user.username,publish_date=date.today(),public=public,text=text) + newDiary = Diary(title=title,author=target.username,publish_date=date.today(),public=public,text=text) session.add(newDiary) session.commit() return jsonify({'status': True}), 201# @@ -152,7 +150,7 @@ def create_diary(): return jsonify({'status':False, 'error':'Invalid authentication token.'}), 200# @app.route('/diary/delete',methods=['POST']) -@auth.login_required +#@auth.login_required def delete_diary(): if request.method=='POST': curr_token = request.json.get('token') @@ -167,7 +165,7 @@ def delete_diary(): return jsonify({'status':False, 'error':'Invalid authentication token.'}), 200# @app.route('/diary/permission',methods=['POST']) -@auth.login_required +#@auth.login_required def change_permission(): if request.method=='POST': curr_token = request.json.get('token') From 5684c6cc72b5d3c4bca57ec57f6a58cc8b45ad47 Mon Sep 17 00:00:00 2001 From: Shin Date: Sat, 24 Feb 2018 14:47:56 +0000 Subject: [PATCH 15/54] fix no diary id --- src/service/app.py | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/src/service/app.py b/src/service/app.py index 521eb3e..2484351 100644 --- a/src/service/app.py +++ b/src/service/app.py @@ -25,7 +25,9 @@ CORS(app) # Remember to update this list -ENDPOINT_LIST = ['/', '/meta/heartbeat', '/meta/members','/users/register'] +ENDPOINT_LIST = ['/', '/meta/heartbeat', '/meta/members','/users/register', + '/users/expire','users/authenticate','/users','/diary (get)','/diary(post)', + '/diary/create','/diary/delete','/diary/permission'] @auth.verify_password @@ -109,11 +111,8 @@ def get_secret_diary(): target = session.query(Token).filter_by(uuid=curr_token).first() if target and not target.expired: diaryList = session.query(Diary).filter_by(author=target.username) - if diaryList.first(): - diaryList_serialized = [d.serialize for d in diaryList.all()] - return jsonify({'status': True, 'result':diaryList_serialized}), 201# - else: - return jsonify({'status': True, 'result':[]}), 201# + diaryList_serialized = [d.serialize for d in diaryList.all()] + return jsonify({'status': True, 'result':diaryList_serialized}), 201# return jsonify({'status': False, 'error': 'Invalid authentication token.'}), 200# @@ -121,12 +120,8 @@ def get_secret_diary(): def get_diary(): if request.method == 'GET': diaryList = session.query(Diary).filter_by(public=True) - if diaryList.first(): - diaryList_serialized = [d.serialize for d in diaryList.all()] - - return jsonify({'status': True,'result':diaryList_serialized }),200# - else: - return jsonify({'status': True, 'result': []}),200# + diaryList_serialized = [d.serialize for d in diaryList.all()] + return jsonify({'status': True,'result':diaryList_serialized }),200# else: return get_secret_diary() @@ -174,10 +169,13 @@ def change_permission(): public = request.json.get('public') id = request.json.get('id') d = session.query(Diary).filter_by(id=id).first() - d.public=public - session.add(d) - session.commit() - return jsonify({'status':True}), 200# + if d: + d.public=public + session.add(d) + session.commit() + return jsonify({'status':True}), 200# + else: + return jsonify({'status':False,'error': 'Diary does not exist'}), 200# else: return jsonify({'status':False, 'error':'Invalid authentication token.'}), 200# From a2de0d7cb8e9a34c6dcc1614a059687f091c04d0 Mon Sep 17 00:00:00 2001 From: Shin Date: Sun, 25 Feb 2018 04:40:59 +0000 Subject: [PATCH 16/54] add requirements file --- src/service/requirements.txt | 3 +++ src/service/requirements.txt~ | 2 ++ 2 files changed, 5 insertions(+) create mode 100644 src/service/requirements.txt create mode 100644 src/service/requirements.txt~ diff --git a/src/service/requirements.txt b/src/service/requirements.txt new file mode 100644 index 0000000..47bb048 --- /dev/null +++ b/src/service/requirements.txt @@ -0,0 +1,3 @@ +sqlalchemy +flask_httpauth +bleach diff --git a/src/service/requirements.txt~ b/src/service/requirements.txt~ new file mode 100644 index 0000000..9bab15c --- /dev/null +++ b/src/service/requirements.txt~ @@ -0,0 +1,2 @@ +sqlalchemy +flask_httpauth From 73733ee57f08969311c779e39033262cee7b0fe3 Mon Sep 17 00:00:00 2001 From: Shin Date: Sun, 25 Feb 2018 04:41:11 +0000 Subject: [PATCH 17/54] app.py --- src/service/app.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/service/app.py b/src/service/app.py index 2484351..1ee2b19 100644 --- a/src/service/app.py +++ b/src/service/app.py @@ -10,6 +10,7 @@ import uuid from flask_httpauth import HTTPBasicAuth from datetime import date +import bleach auth = HTTPBasicAuth() @@ -42,9 +43,9 @@ def verify_password(username,password): def user_registration(): print request.json if request.method == 'POST': - username=request.json.get('username') + username=bleach.clean(request.json.get('username')) password=request.json.get('password') - fullname=request.json.get('fullname') + fullname=bleach.clean(request.json.get('fullname')) age=request.json.get('age') if username is None or password is None or fullname is None: @@ -134,9 +135,9 @@ def create_diary(): target= session.query(Token).filter_by(uuid=curr_token).first() if target and not target.expired: - title = request.json.get('title') + title = bleach.clean(request.json.get('title')) public = request.json.get('public') - text = request.json.get('text') + text = bleach.clean(request.json.get('text')) newDiary = Diary(title=title,author=target.username,publish_date=date.today(),public=public,text=text) session.add(newDiary) session.commit() From ca9f6a9f168eba57b696c481c09bc7d506cfd6a5 Mon Sep 17 00:00:00 2001 From: Shin Date: Sun, 25 Feb 2018 04:43:38 +0000 Subject: [PATCH 18/54] use bleach to santinize user input --- src/service/app.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/service/app.py b/src/service/app.py index 1ee2b19..80b2b22 100644 --- a/src/service/app.py +++ b/src/service/app.py @@ -10,7 +10,7 @@ import uuid from flask_httpauth import HTTPBasicAuth from datetime import date -import bleach +import bleach # santinize library auth = HTTPBasicAuth() @@ -43,6 +43,7 @@ def verify_password(username,password): def user_registration(): print request.json if request.method == 'POST': + # santinize user input when registration username=bleach.clean(request.json.get('username')) password=request.json.get('password') fullname=bleach.clean(request.json.get('fullname')) @@ -135,6 +136,7 @@ def create_diary(): target= session.query(Token).filter_by(uuid=curr_token).first() if target and not target.expired: + # santinize diary content when creating diary title = bleach.clean(request.json.get('title')) public = request.json.get('public') text = bleach.clean(request.json.get('text')) From 06c26f635f8ee5fb55ad455df74b47100b3fe964 Mon Sep 17 00:00:00 2001 From: Liu Chao Date: Tue, 27 Feb 2018 17:56:46 +0800 Subject: [PATCH 19/54] Update requirements.txt --- src/service/requirements.txt | 2 ++ src/service/requirements.txt~ | 2 -- 2 files changed, 2 insertions(+), 2 deletions(-) delete mode 100644 src/service/requirements.txt~ diff --git a/src/service/requirements.txt b/src/service/requirements.txt index 47bb048..324335a 100644 --- a/src/service/requirements.txt +++ b/src/service/requirements.txt @@ -1,3 +1,5 @@ sqlalchemy +flask +flask_cors flask_httpauth bleach diff --git a/src/service/requirements.txt~ b/src/service/requirements.txt~ deleted file mode 100644 index 9bab15c..0000000 --- a/src/service/requirements.txt~ +++ /dev/null @@ -1,2 +0,0 @@ -sqlalchemy -flask_httpauth From 15ebdada837343ed044eaa98e7d9ca6b2e3c4096 Mon Sep 17 00:00:00 2001 From: Liu Chao Date: Sat, 24 Feb 2018 19:42:27 +0800 Subject: [PATCH 20/54] Start react frontend --- src/webapp/README.md | 2434 +++++++++ src/webapp/package.json | 17 + src/webapp/public/favicon.ico | Bin 0 -> 3870 bytes src/webapp/public/index.html | 40 + src/webapp/public/manifest.json | 15 + src/webapp/src/App.css | 28 + src/webapp/src/App.js | 63 + src/webapp/src/App.test.js | 9 + src/webapp/src/index.css | 5 + src/webapp/src/index.js | 8 + src/webapp/src/logo.svg | 7 + src/webapp/src/registerServiceWorker.js | 117 + src/webapp/yarn.lock | 6692 +++++++++++++++++++++++ 13 files changed, 9435 insertions(+) create mode 100644 src/webapp/README.md create mode 100644 src/webapp/package.json create mode 100644 src/webapp/public/favicon.ico create mode 100644 src/webapp/public/index.html create mode 100644 src/webapp/public/manifest.json create mode 100644 src/webapp/src/App.css create mode 100644 src/webapp/src/App.js create mode 100644 src/webapp/src/App.test.js create mode 100644 src/webapp/src/index.css create mode 100644 src/webapp/src/index.js create mode 100644 src/webapp/src/logo.svg create mode 100644 src/webapp/src/registerServiceWorker.js create mode 100644 src/webapp/yarn.lock diff --git a/src/webapp/README.md b/src/webapp/README.md new file mode 100644 index 0000000..d40c87e --- /dev/null +++ b/src/webapp/README.md @@ -0,0 +1,2434 @@ +This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app). + +Below you will find some information on how to perform common tasks.
+You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md). + +## Table of Contents + +- [Updating to New Releases](#updating-to-new-releases) +- [Sending Feedback](#sending-feedback) +- [Folder Structure](#folder-structure) +- [Available Scripts](#available-scripts) + - [npm start](#npm-start) + - [npm test](#npm-test) + - [npm run build](#npm-run-build) + - [npm run eject](#npm-run-eject) +- [Supported Browsers](#supported-browsers) +- [Supported Language Features and Polyfills](#supported-language-features-and-polyfills) +- [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor) +- [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor) +- [Debugging in the Editor](#debugging-in-the-editor) +- [Formatting Code Automatically](#formatting-code-automatically) +- [Changing the Page ``](#changing-the-page-title) +- [Installing a Dependency](#installing-a-dependency) +- [Importing a Component](#importing-a-component) +- [Code Splitting](#code-splitting) +- [Adding a Stylesheet](#adding-a-stylesheet) +- [Post-Processing CSS](#post-processing-css) +- [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc) +- [Adding Images, Fonts, and Files](#adding-images-fonts-and-files) +- [Using the `public` Folder](#using-the-public-folder) + - [Changing the HTML](#changing-the-html) + - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) + - [When to Use the `public` Folder](#when-to-use-the-public-folder) +- [Using Global Variables](#using-global-variables) +- [Adding Bootstrap](#adding-bootstrap) + - [Using a Custom Theme](#using-a-custom-theme) +- [Adding Flow](#adding-flow) +- [Adding a Router](#adding-a-router) +- [Adding Custom Environment Variables](#adding-custom-environment-variables) + - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html) + - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell) + - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env) +- [Can I Use Decorators?](#can-i-use-decorators) +- [Fetching Data with AJAX Requests](#fetching-data-with-ajax-requests) +- [Integrating with an API Backend](#integrating-with-an-api-backend) + - [Node](#node) + - [Ruby on Rails](#ruby-on-rails) +- [Proxying API Requests in Development](#proxying-api-requests-in-development) + - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy) + - [Configuring the Proxy Manually](#configuring-the-proxy-manually) + - [Configuring a WebSocket Proxy](#configuring-a-websocket-proxy) +- [Using HTTPS in Development](#using-https-in-development) +- [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server) +- [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files) +- [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page) +- [Running Tests](#running-tests) + - [Filename Conventions](#filename-conventions) + - [Command Line Interface](#command-line-interface) + - [Version Control Integration](#version-control-integration) + - [Writing Tests](#writing-tests) + - [Testing Components](#testing-components) + - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries) + - [Initializing Test Environment](#initializing-test-environment) + - [Focusing and Excluding Tests](#focusing-and-excluding-tests) + - [Coverage Reporting](#coverage-reporting) + - [Continuous Integration](#continuous-integration) + - [Disabling jsdom](#disabling-jsdom) + - [Snapshot Testing](#snapshot-testing) + - [Editor Integration](#editor-integration) +- [Debugging Tests](#debugging-tests) + - [Debugging Tests in Chrome](#debugging-tests-in-chrome) + - [Debugging Tests in Visual Studio Code](#debugging-tests-in-visual-studio-code) +- [Developing Components in Isolation](#developing-components-in-isolation) + - [Getting Started with Storybook](#getting-started-with-storybook) + - [Getting Started with Styleguidist](#getting-started-with-styleguidist) +- [Publishing Components to npm](#publishing-components-to-npm) +- [Making a Progressive Web App](#making-a-progressive-web-app) + - [Opting Out of Caching](#opting-out-of-caching) + - [Offline-First Considerations](#offline-first-considerations) + - [Progressive Web App Metadata](#progressive-web-app-metadata) +- [Analyzing the Bundle Size](#analyzing-the-bundle-size) +- [Deployment](#deployment) + - [Static Server](#static-server) + - [Other Solutions](#other-solutions) + - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing) + - [Building for Relative Paths](#building-for-relative-paths) + - [Azure](#azure) + - [Firebase](#firebase) + - [GitHub Pages](#github-pages) + - [Heroku](#heroku) + - [Netlify](#netlify) + - [Now](#now) + - [S3 and CloudFront](#s3-and-cloudfront) + - [Surge](#surge) +- [Advanced Configuration](#advanced-configuration) +- [Troubleshooting](#troubleshooting) + - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes) + - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra) + - [`npm run build` exits too early](#npm-run-build-exits-too-early) + - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) + - [`npm run build` fails to minify](#npm-run-build-fails-to-minify) + - [Moment.js locales are missing](#momentjs-locales-are-missing) +- [Alternatives to Ejecting](#alternatives-to-ejecting) +- [Something Missing?](#something-missing) + +## Updating to New Releases + +Create React App is divided into two packages: + +* `create-react-app` is a global command-line utility that you use to create new projects. +* `react-scripts` is a development dependency in the generated projects (including this one). + +You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`. + +When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically. + +To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions. + +In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes. + +We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly. + +## Sending Feedback + +We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues). + +## Folder Structure + +After creation, your project should look like this: + +``` +my-app/ + README.md + node_modules/ + package.json + public/ + index.html + favicon.ico + src/ + App.css + App.js + App.test.js + index.css + index.js + logo.svg +``` + +For the project to build, **these files must exist with exact filenames**: + +* `public/index.html` is the page template; +* `src/index.js` is the JavaScript entry point. + +You can delete or rename the other files. + +You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.<br> +You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them. + +Only files inside `public` can be used from `public/index.html`.<br> +Read instructions below for using assets from JavaScript and HTML. + +You can, however, create more top-level directories.<br> +They will not be included in the production build so you can use them for things like documentation. + +## Available Scripts + +In the project directory, you can run: + +### `npm start` + +Runs the app in the development mode.<br> +Open [http://localhost:3000](http://localhost:3000) to view it in the browser. + +The page will reload if you make edits.<br> +You will also see any lint errors in the console. + +### `npm test` + +Launches the test runner in the interactive watch mode.<br> +See the section about [running tests](#running-tests) for more information. + +### `npm run build` + +Builds the app for production to the `build` folder.<br> +It correctly bundles React in production mode and optimizes the build for the best performance. + +The build is minified and the filenames include the hashes.<br> +Your app is ready to be deployed! + +See the section about [deployment](#deployment) for more information. + +### `npm run eject` + +**Note: this is a one-way operation. Once you `eject`, you can’t go back!** + +If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. + +Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. + +You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. + +## Supported Browsers + +By default, the generated project uses the latest version of React. + +You can refer [to the React documentation](https://reactjs.org/docs/react-dom.html#browser-support) for more information about supported browsers. + +## Supported Language Features and Polyfills + +This project supports a superset of the latest JavaScript standard.<br> +In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports: + +* [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016). +* [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017). +* [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal). +* [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal) +* [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (part of stage 3 proposal). +* [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax. + +Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-). + +While we recommend using experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future. + +Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**: + +* [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign). +* [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise). +* [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch). + +If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them. + +Also note that using some newer syntax features like `for...of` or `[...nonArrayValue]` causes Babel to emit code that depends on ES6 runtime features and might not work without a polyfill. When in doubt, use [Babel REPL](https://babeljs.io/repl/) to see what any specific syntax compiles down to. + +## Syntax Highlighting in the Editor + +To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered. + +## Displaying Lint Output in the Editor + +>Note: this feature is available with `react-scripts@0.2.0` and higher.<br> +>It also only works with npm 3 or higher. + +Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint. + +They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do. + +You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root: + +```js +{ + "extends": "react-app" +} +``` + +Now your editor should report the linting warnings. + +Note that even if you edit your `.eslintrc` file further, these changes will **only affect the editor integration**. They won’t affect the terminal and in-browser lint output. This is because Create React App intentionally provides a minimal set of rules that find common mistakes. + +If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules. + +## Debugging in the Editor + +**This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).** + +Visual Studio Code and WebStorm support debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools. + +### Visual Studio Code + +You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed. + +Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory. + +```json +{ + "version": "0.2.0", + "configurations": [{ + "name": "Chrome", + "type": "chrome", + "request": "launch", + "url": "http://localhost:3000", + "webRoot": "${workspaceRoot}/src", + "sourceMapPathOverrides": { + "webpack:///src/*": "${webRoot}/*" + } + }] +} +``` +>Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). + +Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor. + +Having problems with VS Code Debugging? Please see their [troubleshooting guide](https://github.com/Microsoft/vscode-chrome-debug/blob/master/README.md#troubleshooting). + +### WebStorm + +You would need to have [WebStorm](https://www.jetbrains.com/webstorm/) and [JetBrains IDE Support](https://chrome.google.com/webstore/detail/jetbrains-ide-support/hmhgeddbohgjknpmjagkdomcpobmllji) Chrome extension installed. + +In the WebStorm menu `Run` select `Edit Configurations...`. Then click `+` and select `JavaScript Debug`. Paste `http://localhost:3000` into the URL field and save the configuration. + +>Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). + +Start your app by running `npm start`, then press `^D` on macOS or `F9` on Windows and Linux or click the green debug icon to start debugging in WebStorm. + +The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine. + +## Formatting Code Automatically + +Prettier is an opinionated code formatter with support for JavaScript, CSS and JSON. With Prettier you can format the code you write automatically to ensure a code style within your project. See the [Prettier's GitHub page](https://github.com/prettier/prettier) for more information, and look at this [page to see it in action](https://prettier.github.io/prettier/). + +To format our code whenever we make a commit in git, we need to install the following dependencies: + +```sh +npm install --save husky lint-staged prettier +``` + +Alternatively you may use `yarn`: + +```sh +yarn add husky lint-staged prettier +``` + +* `husky` makes it easy to use githooks as if they are npm scripts. +* `lint-staged` allows us to run scripts on staged files in git. See this [blog post about lint-staged to learn more about it](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8). +* `prettier` is the JavaScript formatter we will run before commits. + +Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root. + +Add the following line to `scripts` section: + +```diff + "scripts": { ++ "precommit": "lint-staged", + "start": "react-scripts start", + "build": "react-scripts build", +``` + +Next we add a 'lint-staged' field to the `package.json`, for example: + +```diff + "dependencies": { + // ... + }, ++ "lint-staged": { ++ "src/**/*.{js,jsx,json,css}": [ ++ "prettier --single-quote --write", ++ "git add" ++ ] ++ }, + "scripts": { +``` + +Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run `./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx,json,css}"` to format your entire project for the first time. + +Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://prettier.io/docs/en/editors.html) on the Prettier GitHub page. + +## Changing the Page `<title>` + +You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` tag in it to change the title from “React App” to anything else. + +Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML. + +If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library. + +If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files). + +## Installing a Dependency + +The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`: + +```sh +npm install --save react-router +``` + +Alternatively you may use `yarn`: + +```sh +yarn add react-router +``` + +This works for any library, not just `react-router`. + +## Importing a Component + +This project setup supports ES6 modules thanks to Babel.<br> +While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead. + +For example: + +### `Button.js` + +```js +import React, { Component } from 'react'; + +class Button extends Component { + render() { + // ... + } +} + +export default Button; // Don’t forget to use export default! +``` + +### `DangerButton.js` + + +```js +import React, { Component } from 'react'; +import Button from './Button'; // Import a component from another file + +class DangerButton extends Component { + render() { + return <Button color="red" />; + } +} + +export default DangerButton; +``` + +Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes. + +We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`. + +Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like. + +Learn more about ES6 modules: + +* [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281) +* [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html) +* [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules) + +## Code Splitting + +Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand. + +This project setup supports code splitting via [dynamic `import()`](http://2ality.com/2017/01/import-operator.html#loading-code-on-demand). Its [proposal](https://github.com/tc39/proposal-dynamic-import) is in stage 3. The `import()` function-like form takes the module name as an argument and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which always resolves to the namespace object of the module. + +Here is an example: + +### `moduleA.js` + +```js +const moduleA = 'Hello'; + +export { moduleA }; +``` +### `App.js` + +```js +import React, { Component } from 'react'; + +class App extends Component { + handleClick = () => { + import('./moduleA') + .then(({ moduleA }) => { + // Use moduleA + }) + .catch(err => { + // Handle failure + }); + }; + + render() { + return ( + <div> + <button onClick={this.handleClick}>Load</button> + </div> + ); + } +} + +export default App; +``` + +This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button. + +You can also use it with `async` / `await` syntax if you prefer it. + +### With React Router + +If you are using React Router check out [this tutorial](http://serverless-stack.com/chapters/code-splitting-in-create-react-app.html) on how to use code splitting with it. You can find the companion GitHub repository [here](https://github.com/AnomalyInnovations/serverless-stack-demo-client/tree/code-splitting-in-create-react-app). + +Also check out the [Code Splitting](https://reactjs.org/docs/code-splitting.html) section in React documentation. + +## Adding a Stylesheet + +This project setup uses [Webpack](https://webpack.js.org/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**: + +### `Button.css` + +```css +.Button { + padding: 20px; +} +``` + +### `Button.js` + +```js +import React, { Component } from 'react'; +import './Button.css'; // Tell Webpack that Button.js uses these styles + +class Button extends Component { + render() { + // You can use them as regular CSS styles + return <div className="Button" />; + } +} +``` + +**This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-ui-engineering/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack. + +In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output. + +If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool. + +## Post-Processing CSS + +This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it. + +For example, this: + +```css +.App { + display: flex; + flex-direction: row; + align-items: center; +} +``` + +becomes this: + +```css +.App { + display: -webkit-box; + display: -ms-flexbox; + display: flex; + -webkit-box-orient: horizontal; + -webkit-box-direction: normal; + -ms-flex-direction: row; + flex-direction: row; + -webkit-box-align: center; + -ms-flex-align: center; + align-items: center; +} +``` + +If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling). + +## Adding a CSS Preprocessor (Sass, Less etc.) + +Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `<AcceptButton>` and `<RejectButton>` components, we recommend creating a `<Button>` component with its own `.Button` styles, that both `<AcceptButton>` and `<RejectButton>` can render (but [not inherit](https://facebook.github.io/react/docs/composition-vs-inheritance.html)). + +Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition. You can, however, integrate a CSS preprocessor if you find it valuable. In this walkthrough, we will be using Sass, but you can also use Less, or another alternative. + +First, let’s install the command-line interface for Sass: + +```sh +npm install --save node-sass-chokidar +``` + +Alternatively you may use `yarn`: + +```sh +yarn add node-sass-chokidar +``` + +Then in `package.json`, add the following lines to `scripts`: + +```diff + "scripts": { ++ "build-css": "node-sass-chokidar src/ -o src/", ++ "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", + "start": "react-scripts start", + "build": "react-scripts build", + "test": "react-scripts test --env=jsdom", +``` + +>Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessor’s documentation. + +Now you can rename `src/App.css` to `src/App.scss` and run `npm run watch-css`. The watcher will find every Sass file in `src` subdirectories, and create a corresponding CSS file next to it, in our case overwriting `src/App.css`. Since `src/App.js` still imports `src/App.css`, the styles become a part of your application. You can now edit `src/App.scss`, and `src/App.css` will be regenerated. + +To share variables between Sass files, you can use Sass imports. For example, `src/App.scss` and other component style files could include `@import "./shared.scss";` with variable definitions. + +To enable importing files without using relative paths, you can add the `--include-path` option to the command in `package.json`. + +``` +"build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/", +"watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive", +``` + +This will allow you to do imports like + +```scss +@import 'styles/_colors.scss'; // assuming a styles directory under src/ +@import 'nprogress/nprogress'; // importing a css file from the nprogress node module +``` + +At this point you might want to remove all CSS files from the source control, and add `src/**/*.css` to your `.gitignore` file. It is generally a good practice to keep the build products outside of the source control. + +As a final step, you may find it convenient to run `watch-css` automatically with `npm start`, and run `build-css` as a part of `npm run build`. You can use the `&&` operator to execute two scripts sequentially. However, there is no cross-platform way to run two scripts in parallel, so we will install a package for this: + +```sh +npm install --save npm-run-all +``` + +Alternatively you may use `yarn`: + +```sh +yarn add npm-run-all +``` + +Then we can change `start` and `build` scripts to include the CSS preprocessor commands: + +```diff + "scripts": { + "build-css": "node-sass-chokidar src/ -o src/", + "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", +- "start": "react-scripts start", +- "build": "react-scripts build", ++ "start-js": "react-scripts start", ++ "start": "npm-run-all -p watch-css start-js", ++ "build-js": "react-scripts build", ++ "build": "npm-run-all build-css build-js", + "test": "react-scripts test --env=jsdom", + "eject": "react-scripts eject" + } +``` + +Now running `npm start` and `npm run build` also builds Sass files. + +**Why `node-sass-chokidar`?** + +`node-sass` has been reported as having the following issues: + +- `node-sass --watch` has been reported to have *performance issues* in certain conditions when used in a virtual machine or with docker. + +- Infinite styles compiling [#1939](https://github.com/facebookincubator/create-react-app/issues/1939) + +- `node-sass` has been reported as having issues with detecting new files in a directory [#1891](https://github.com/sass/node-sass/issues/1891) + + `node-sass-chokidar` is used here as it addresses these issues. + +## Adding Images, Fonts, and Files + +With Webpack, using static assets like images and fonts works similarly to CSS. + +You can **`import` a file right in a JavaScript module**. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the `src` attribute of an image or the `href` of a link to a PDF. + +To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a [data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png. SVG files are excluded due to [#1153](https://github.com/facebookincubator/create-react-app/issues/1153). + +Here is an example: + +```js +import React from 'react'; +import logo from './logo.png'; // Tell Webpack this JS file uses this image + +console.log(logo); // /logo.84287d09.png + +function Header() { + // Import result is the URL of your image + return <img src={logo} alt="Logo" />; +} + +export default Header; +``` + +This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths. + +This works in CSS too: + +```css +.Logo { + background-image: url(./logo.png); +} +``` + +Webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets. + +Please be advised that this is also a custom feature of Webpack. + +**It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).<br> +An alternative way of handling static assets is described in the next section. + +## Using the `public` Folder + +>Note: this feature is available with `react-scripts@0.5.0` and higher. + +### Changing the HTML + +The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). +The `<script>` tag with the compiled code will be added to it automatically during the build process. + +### Adding Assets Outside of the Module System + +You can also add other assets to the `public` folder. + +Note that we normally encourage you to `import` assets in JavaScript files instead. +For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-fonts-and-files). +This mechanism provides a number of benefits: + +* Scripts and stylesheets get minified and bundled together to avoid extra network requests. +* Missing files cause compilation errors instead of 404 errors for your users. +* Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. + +However there is an **escape hatch** that you can use to add an asset outside of the module system. + +If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. + +Inside `index.html`, you can use it like this: + +```html +<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> +``` + +Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. + +When you run `npm run build`, Create React App will substitute `%PUBLIC_URL%` with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL. + +In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: + +```js +render() { + // Note: this is an escape hatch and should be used sparingly! + // Normally we recommend using `import` for getting asset URLs + // as described in “Adding Images and Fonts” above this section. + return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; +} +``` + +Keep in mind the downsides of this approach: + +* None of the files in `public` folder get post-processed or minified. +* Missing files will not be called at compilation time, and will cause 404 errors for your users. +* Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. + +### When to Use the `public` Folder + +Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-fonts-and-files) from JavaScript. +The `public` folder is useful as a workaround for a number of less common cases: + +* You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). +* You have thousands of images and need to dynamically reference their paths. +* You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. +* Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. + +Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. + +## Using Global Variables + +When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable. + +You can avoid this by reading the global variable explicitly from the `window` object, for example: + +```js +const $ = window.$; +``` + +This makes it obvious you are using a global variable intentionally rather than because of a typo. + +Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. + +## Adding Bootstrap + +You don’t have to use [React Bootstrap](https://react-bootstrap.github.io) together with React but it is a popular library for integrating Bootstrap with React apps. If you need it, you can integrate it with Create React App by following these steps: + +Install React Bootstrap and Bootstrap from npm. React Bootstrap does not include Bootstrap CSS so this needs to be installed as well: + +```sh +npm install --save react-bootstrap bootstrap@3 +``` + +Alternatively you may use `yarn`: + +```sh +yarn add react-bootstrap bootstrap@3 +``` + +Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your ```src/index.js``` file: + +```js +import 'bootstrap/dist/css/bootstrap.css'; +import 'bootstrap/dist/css/bootstrap-theme.css'; +// Put any other imports below so that CSS from your +// components takes precedence over default styles. +``` + +Import required React Bootstrap components within ```src/App.js``` file or your custom component files: + +```js +import { Navbar, Jumbotron, Button } from 'react-bootstrap'; +``` + +Now you are ready to use the imported React Bootstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/gaearon/85d8c067f6af1e56277c82d19fd4da7b/raw/6158dd991b67284e9fc8d70b9d973efe87659d72/App.js) redone using React Bootstrap. + +### Using a Custom Theme + +Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br> +We suggest the following approach: + +* Create a new package that depends on the package you wish to customize, e.g. Bootstrap. +* Add the necessary build steps to tweak the theme, and publish your package on npm. +* Install your own theme npm package as a dependency of your app. + +Here is an example of adding a [customized Bootstrap](https://medium.com/@tacomanator/customizing-create-react-app-aa9ffb88165) that follows these steps. + +## Adding Flow + +Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept. + +Recent versions of [Flow](http://flowtype.org/) work with Create React App projects out of the box. + +To add Flow to a Create React App project, follow these steps: + +1. Run `npm install --save flow-bin` (or `yarn add flow-bin`). +2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. +3. Run `npm run flow init` (or `yarn flow init`) to create a [`.flowconfig` file](https://flowtype.org/docs/advanced-configuration.html) in the root directory. +4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). + +Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors. +You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. +In the future we plan to integrate it into Create React App even more closely. + +To learn more about Flow, check out [its documentation](https://flowtype.org/). + +## Adding a Router + +Create React App doesn't prescribe a specific routing solution, but [React Router](https://reacttraining.com/react-router/) is the most popular one. + +To add it, run: + +```sh +npm install --save react-router-dom +``` + +Alternatively you may use `yarn`: + +```sh +yarn add react-router-dom +``` + +To try it, delete all the code in `src/App.js` and replace it with any of the examples on its website. The [Basic Example](https://reacttraining.com/react-router/web/example/basic) is a good place to get started. + +Note that [you may need to configure your production server to support client-side routing](#serving-apps-with-client-side-routing) before deploying your app. + +## Adding Custom Environment Variables + +>Note: this feature is available with `react-scripts@0.2.3` and higher. + +Your project can consume variables declared in your environment as if they were declared locally in your JS files. By +default you will have `NODE_ENV` defined for you, and any other environment variables starting with +`REACT_APP_`. + +**The environment variables are embedded during the build time**. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like [described here](#injecting-data-from-the-server-into-the-page). Alternatively you can rebuild the app on the server anytime you change them. + +>Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. + +These environment variables will be defined for you on `process.env`. For example, having an environment +variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`. + +There is also a special built-in environment variable called `NODE_ENV`. You can read it from `process.env.NODE_ENV`. When you run `npm start`, it is always equal to `'development'`, when you run `npm test` it is always equal to `'test'`, and when you run `npm run build` to make a production bundle, it is always equal to `'production'`. **You cannot override `NODE_ENV` manually.** This prevents developers from accidentally deploying a slow development build to production. + +These environment variables can be useful for displaying information conditionally based on where the project is +deployed or consuming sensitive data that lives outside of version control. + +First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined +in the environment inside a `<form>`: + +```jsx +render() { + return ( + <div> + <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> + <form> + <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> + </form> + </div> + ); +} +``` + +During the build, `process.env.REACT_APP_SECRET_CODE` will be replaced with the current value of the `REACT_APP_SECRET_CODE` environment variable. Remember that the `NODE_ENV` variable will be set for you automatically. + +When you load the app in the browser and inspect the `<input>`, you will see its value set to `abcdef`, and the bold text will show the environment provided when using `npm start`: + +```html +<div> + <small>You are running this application in <b>development</b> mode.</small> + <form> + <input type="hidden" value="abcdef" /> + </form> +</div> +``` + +The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this +value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in +a `.env` file. Both of these ways are described in the next few sections. + +Having access to the `NODE_ENV` is also useful for performing actions conditionally: + +```js +if (process.env.NODE_ENV !== 'production') { + analytics.disable(); +} +``` + +When you compile the app with `npm run build`, the minification step will strip out this condition, and the resulting bundle will be smaller. + +### Referencing Environment Variables in the HTML + +>Note: this feature is available with `react-scripts@0.9.0` and higher. + +You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example: + +```html +<title>%REACT_APP_WEBSITE_NAME% +``` + +Note that the caveats from the above section apply: + +* Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work. +* The environment variables are injected at build time. If you need to inject them at runtime, [follow this approach instead](#generating-dynamic-meta-tags-on-the-server). + +### Adding Temporary Environment Variables In Your Shell + +Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the +life of the shell session. + +#### Windows (cmd.exe) + +```cmd +set "REACT_APP_SECRET_CODE=abcdef" && npm start +``` + +(Note: Quotes around the variable assignment are required to avoid a trailing whitespace.) + +#### Windows (Powershell) + +```Powershell +($env:REACT_APP_SECRET_CODE = "abcdef") -and (npm start) +``` + +#### Linux, macOS (Bash) + +```bash +REACT_APP_SECRET_CODE=abcdef npm start +``` + +### Adding Development Environment Variables In `.env` + +>Note: this feature is available with `react-scripts@0.5.0` and higher. + +To define permanent environment variables, create a file called `.env` in the root of your project: + +``` +REACT_APP_SECRET_CODE=abcdef +``` +>Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid [accidentally exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. + +`.env` files **should be** checked into source control (with the exclusion of `.env*.local`). + +#### What other `.env` files can be used? + +>Note: this feature is **available with `react-scripts@1.0.0` and higher**. + +* `.env`: Default. +* `.env.local`: Local overrides. **This file is loaded for all environments except test.** +* `.env.development`, `.env.test`, `.env.production`: Environment-specific settings. +* `.env.development.local`, `.env.test.local`, `.env.production.local`: Local overrides of environment-specific settings. + +Files on the left have more priority than files on the right: + +* `npm start`: `.env.development.local`, `.env.development`, `.env.local`, `.env` +* `npm run build`: `.env.production.local`, `.env.production`, `.env.local`, `.env` +* `npm test`: `.env.test.local`, `.env.test`, `.env` (note `.env.local` is missing) + +These variables will act as the defaults if the machine does not explicitly set them.
+Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details. + +>Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need +these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars). + +#### Expanding Environment Variables In `.env` + +>Note: this feature is available with `react-scripts@1.1.0` and higher. + +Expand variables already on your machine for use in your `.env` file (using [dotenv-expand](https://github.com/motdotla/dotenv-expand)). + +For example, to get the environment variable `npm_package_version`: + +``` +REACT_APP_VERSION=$npm_package_version +# also works: +# REACT_APP_VERSION=${npm_package_version} +``` + +Or expand variables local to the current `.env` file: + +``` +DOMAIN=www.example.com +REACT_APP_FOO=$DOMAIN/foo +REACT_APP_BAR=$DOMAIN/bar +``` + +## Can I Use Decorators? + +Many popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.
+Create React App doesn’t support decorator syntax at the moment because: + +* It is an experimental proposal and is subject to change. +* The current specification version is not officially supported by Babel. +* If the specification changes, we won’t be able to write a codemod because we don’t use them internally at Facebook. + +However in many cases you can rewrite decorator-based code without decorators just as fine.
+Please refer to these two threads for reference: + +* [#214](https://github.com/facebookincubator/create-react-app/issues/214) +* [#411](https://github.com/facebookincubator/create-react-app/issues/411) + +Create React App will add decorator support when the specification advances to a stable stage. + +## Fetching Data with AJAX Requests + +React doesn't prescribe a specific approach to data fetching, but people commonly use either a library like [axios](https://github.com/axios/axios) or the [`fetch()` API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) provided by the browser. Conveniently, Create React App includes a polyfill for `fetch()` so you can use it without worrying about the browser support. + +The global `fetch` function allows to easily makes AJAX requests. It takes in a URL as an input and returns a `Promise` that resolves to a `Response` object. You can find more information about `fetch` [here](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch). + +This project also includes a [Promise polyfill](https://github.com/then/promise) which provides a full implementation of Promises/A+. A Promise represents the eventual result of an asynchronous operation, you can find more information about Promises [here](https://www.promisejs.org/) and [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). Both axios and `fetch()` use Promises under the hood. You can also use the [`async / await`](https://davidwalsh.name/async-await) syntax to reduce the callback nesting. + +You can learn more about making AJAX requests from React components in [the FAQ entry on the React website](https://reactjs.org/docs/faq-ajax.html). + +## Integrating with an API Backend + +These tutorials will help you to integrate your app with an API backend running on another port, +using `fetch()` to access it. + +### Node +Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). +You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo). + +### Ruby on Rails + +Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). +You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo-rails). + +## Proxying API Requests in Development + +>Note: this feature is available with `react-scripts@0.2.3` and higher. + +People often serve the front-end React app from the same host and port as their backend implementation.
+For example, a production setup might look like this after the app is deployed: + +``` +/ - static server returns index.html with React app +/todos - static server returns index.html with React app +/api/todos - server handles any /api/* requests using the backend implementation +``` + +Such setup is **not** required. However, if you **do** have a setup like this, it is convenient to write requests like `fetch('/api/todos')` without worrying about redirecting them to another host or port during development. + +To tell the development server to proxy any unknown requests to your API server in development, add a `proxy` field to your `package.json`, for example: + +```js + "proxy": "http://localhost:4000", +``` + +This way, when you `fetch('/api/todos')` in development, the development server will recognize that it’s not a static asset, and will proxy your request to `http://localhost:4000/api/todos` as a fallback. The development server will **only** attempt to send requests without `text/html` in its `Accept` header to the proxy. + +Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: + +``` +Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. +``` + +Keep in mind that `proxy` only has effect in development (with `npm start`), and it is up to you to ensure that URLs like `/api/todos` point to the right thing in production. You don’t have to use the `/api` prefix. Any unrecognized request without a `text/html` accept header will be redirected to the specified `proxy`. + +The `proxy` option supports HTTP, HTTPS and WebSocket connections.
+If the `proxy` option is **not** flexible enough for you, alternatively you can: + +* [Configure the proxy yourself](#configuring-the-proxy-manually) +* Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). +* Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. + +### "Invalid Host Header" Errors After Configuring Proxy + +When you enable the `proxy` option, you opt into a more strict set of host checks. This is necessary because leaving the backend open to remote hosts makes your computer vulnerable to DNS rebinding attacks. The issue is explained in [this article](https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a) and [this issue](https://github.com/webpack/webpack-dev-server/issues/887). + +This shouldn’t affect you when developing on `localhost`, but if you develop remotely like [described here](https://github.com/facebookincubator/create-react-app/issues/2271), you will see this error in the browser after enabling the `proxy` option: + +>Invalid Host header + +To work around it, you can specify your public development host in a file called `.env.development` in the root of your project: + +``` +HOST=mypublicdevhost.com +``` + +If you restart the development server now and load the app from the specified host, it should work. + +If you are still having issues or if you’re using a more exotic environment like a cloud editor, you can bypass the host check completely by adding a line to `.env.development.local`. **Note that this is dangerous and exposes your machine to remote code execution from malicious websites:** + +``` +# NOTE: THIS IS DANGEROUS! +# It exposes your machine to attacks from the websites you visit. +DANGEROUSLY_DISABLE_HOST_CHECK=true +``` + +We don’t recommend this approach. + +### Configuring the Proxy Manually + +>Note: this feature is available with `react-scripts@1.0.0` and higher. + +If the `proxy` option is **not** flexible enough for you, you can specify an object in the following form (in `package.json`).
+You may also specify any configuration value [`http-proxy-middleware`](https://github.com/chimurai/http-proxy-middleware#options) or [`http-proxy`](https://github.com/nodejitsu/node-http-proxy#options) supports. +```js +{ + // ... + "proxy": { + "/api": { + "target": "", + "ws": true + // ... + } + } + // ... +} +``` + +All requests matching this path will be proxies, no exceptions. This includes requests for `text/html`, which the standard `proxy` option does not proxy. + +If you need to specify multiple proxies, you may do so by specifying additional entries. +Matches are regular expressions, so that you can use a regexp to match multiple paths. +```js +{ + // ... + "proxy": { + // Matches any request starting with /api + "/api": { + "target": "", + "ws": true + // ... + }, + // Matches any request starting with /foo + "/foo": { + "target": "", + "ssl": true, + "pathRewrite": { + "^/foo": "/foo/beta" + } + // ... + }, + // Matches /bar/abc.html but not /bar/sub/def.html + "/bar/[^/]*[.]html": { + "target": "", + // ... + }, + // Matches /baz/abc.html and /baz/sub/def.html + "/baz/.*/.*[.]html": { + "target": "" + // ... + } + } + // ... +} +``` + +### Configuring a WebSocket Proxy + +When setting up a WebSocket proxy, there are a some extra considerations to be aware of. + +If you’re using a WebSocket engine like [Socket.io](https://socket.io/), you must have a Socket.io server running that you can use as the proxy target. Socket.io will not work with a standard WebSocket server. Specifically, don't expect Socket.io to work with [the websocket.org echo test](http://websocket.org/echo.html). + +There’s some good documentation available for [setting up a Socket.io server](https://socket.io/docs/). + +Standard WebSockets **will** work with a standard WebSocket server as well as the websocket.org echo test. You can use libraries like [ws](https://github.com/websockets/ws) for the server, with [native WebSockets in the browser](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket). + +Either way, you can proxy WebSocket requests manually in `package.json`: + +```js +{ + // ... + "proxy": { + "/socket": { + // Your compatible WebSocket server + "target": "ws://", + // Tell http-proxy-middleware that this is a WebSocket proxy. + // Also allows you to proxy WebSocket requests without an additional HTTP request + // https://github.com/chimurai/http-proxy-middleware#external-websocket-upgrade + "ws": true + // ... + } + } + // ... +} +``` + +## Using HTTPS in Development + +>Note: this feature is available with `react-scripts@0.4.0` and higher. + +You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS. + +To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: + +#### Windows (cmd.exe) + +```cmd +set HTTPS=true&&npm start +``` + +#### Windows (Powershell) + +```Powershell +($env:HTTPS = $true) -and (npm start) +``` + +(Note: the lack of whitespace is intentional.) + +#### Linux, macOS (Bash) + +```bash +HTTPS=true npm start +``` + +Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. + +## Generating Dynamic `` Tags on the Server + +Since Create React App doesn’t support server rendering, you might be wondering how to make `` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this: + +```html + + + + + +``` + +Then, on the server, regardless of the backend you use, you can read `index.html` into memory and replace `__OG_TITLE__`, `__OG_DESCRIPTION__`, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML! + +If you use a Node server, you can even share the route matching logic between the client and the server. However duplicating it also works fine in simple cases. + +## Pre-Rendering into Static HTML Files + +If you’re hosting your `build` with a static hosting provider you can use [react-snapshot](https://www.npmjs.com/package/react-snapshot) or [react-snap](https://github.com/stereobooster/react-snap) to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydrated”, when the JavaScript bundle has loaded. + +There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. + +The primary benefit of pre-rendering is that you get the core content of each page _with_ the HTML payload—regardless of whether or not your JavaScript bundle successfully downloads. It also increases the likelihood that each route of your application will be picked up by search engines. + +You can read more about [zero-configuration pre-rendering (also called snapshotting) here](https://medium.com/superhighfives/an-almost-static-stack-6df0a2791319). + +## Injecting Data from the Server into the Page + +Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example: + +```js + + + + +``` + +Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data right before sending the response. The client code can then read `window.SERVER_DATA` to use it. **Make sure to [sanitize the JSON before sending it to the client](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to XSS attacks.** + +## Running Tests + +>Note: this feature is available with `react-scripts@0.3.0` and higher.
+>[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030) + +Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try. + +Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness. + +While Jest provides browser globals such as `window` thanks to [jsdom](https://github.com/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks. + +We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App. + +### Filename Conventions + +Jest will look for test files with any of the following popular naming conventions: + +* Files with `.js` suffix in `__tests__` folders. +* Files with `.test.js` suffix. +* Files with `.spec.js` suffix. + +The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. + +We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects. + +### Command Line Interface + +When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code. + +The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage” note that the watcher prints after every run: + +![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) + +### Version Control Integration + +By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests run fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests. + +Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests. + +Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository. + +### Writing Tests + +To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended. + +Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: + +```js +import sum from './sum'; + +it('sums numbers', () => { + expect(sum(1, 2)).toEqual(3); + expect(sum(2, 2)).toEqual(4); +}); +``` + +All `expect()` matchers supported by Jest are [extensively documented here](https://facebook.github.io/jest/docs/en/expect.html#content).
+You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](https://facebook.github.io/jest/docs/en/expect.html#tohavebeencalled) to create “spies” or mock functions. + +### Testing Components + +There is a broad spectrum of component testing techniques. They range from a “smoke test” verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes. + +Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components: + +```js +import React from 'react'; +import ReactDOM from 'react-dom'; +import App from './App'; + +it('renders without crashing', () => { + const div = document.createElement('div'); + ReactDOM.render(, div); +}); +``` + +This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot of value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.js`. + +When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior. + +If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). To install it, run: + +```sh +npm install --save enzyme enzyme-adapter-react-16 react-test-renderer +``` + +Alternatively you may use `yarn`: + +```sh +yarn add enzyme enzyme-adapter-react-16 react-test-renderer +``` + +As of Enzyme 3, you will need to install Enzyme along with an Adapter corresponding to the version of React you are using. (The examples above use the adapter for React 16.) + +The adapter will also need to be configured in your [global setup file](#initializing-test-environment): + +#### `src/setupTests.js` +```js +import { configure } from 'enzyme'; +import Adapter from 'enzyme-adapter-react-16'; + +configure({ adapter: new Adapter() }); +``` + +>Note: Keep in mind that if you decide to "eject" before creating `src/setupTests.js`, the resulting `package.json` file won't contain any reference to it. [Read here](#initializing-test-environment) to learn how to add this after ejecting. + +Now you can write a smoke test with it: + +```js +import React from 'react'; +import { shallow } from 'enzyme'; +import App from './App'; + +it('renders without crashing', () => { + shallow(); +}); +``` + +Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a ` + + ); + } +} + +export default Login; diff --git a/src/webapp/src/utils/API_Endpoints.js b/src/webapp/src/utils/API_Endpoints.js new file mode 100644 index 0000000..06f2eea --- /dev/null +++ b/src/webapp/src/utils/API_Endpoints.js @@ -0,0 +1,22 @@ +const BASE_API = 'http://localhost:8080'; + +const relativePaths = { + get_members: '/meta/members', + authenticate_user: '/users/authenticate', + register_user: '/users/register', + expire_user: '/users/expire', + get_user: '/users', + get_public_diaries: '/diary', + get_private_diaries: '/diary', + create_diary: '/diary/create', + delete_diary: '/diary/delete', + toggle_diary_permission: '/diary/permission' +}; + +const API_Endpoints = {}; + +Object.keys(relativePaths).forEach(key => { + API_Endpoints[key] = `${BASE_API}${relativePaths[key]}`; +}); + +export default API_Endpoints; diff --git a/src/webapp/src/utils/ajax_get.js b/src/webapp/src/utils/ajax_get.js index 6de5eb6..b93a41c 100644 --- a/src/webapp/src/utils/ajax_get.js +++ b/src/webapp/src/utils/ajax_get.js @@ -1,5 +1,3 @@ -const API_ENDPOINT = 'http://localhost:8080'; - const ajax_get = function(url, callback) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { @@ -16,9 +14,8 @@ const ajax_get = function(url, callback) { }; xmlhttp.open('GET', url, true); + xmlhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); xmlhttp.send(); }; -export { API_ENDPOINT }; - export default ajax_get; diff --git a/src/webapp/src/utils/ajax_post.js b/src/webapp/src/utils/ajax_post.js new file mode 100644 index 0000000..b84fcb4 --- /dev/null +++ b/src/webapp/src/utils/ajax_post.js @@ -0,0 +1,21 @@ +const ajax_post = function(url, data = {}, callback) { + var xmlhttp = new XMLHttpRequest(); + xmlhttp.onreadystatechange = function() { + if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { + console.log('responseText:' + xmlhttp.responseText); + try { + var data = JSON.parse(xmlhttp.responseText); + } catch (err) { + console.log(err.message + ' in ' + xmlhttp.responseText); + return; + } + callback(data); + } + }; + + xmlhttp.open('POST', url, true); + xmlhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); + xmlhttp.send(JSON.stringify(data)); +}; + +export default ajax_post; From f28466aa424c0ce9b4312008aa84b4177337eed5 Mon Sep 17 00:00:00 2001 From: Liu Chao Date: Sun, 25 Feb 2018 08:49:07 +0800 Subject: [PATCH 23/54] Add sign up page --- src/service/app.py | 24 +++-- src/webapp/src/App.js | 3 + src/webapp/src/components/Signup.js | 136 ++++++++++++++++++++++++++++ 3 files changed, 154 insertions(+), 9 deletions(-) create mode 100644 src/webapp/src/components/Signup.js diff --git a/src/service/app.py b/src/service/app.py index 70c5c4d..e7ee872 100644 --- a/src/service/app.py +++ b/src/service/app.py @@ -42,17 +42,23 @@ def verify_password(username, password): @app.route("/users/register", methods=['POST']) def user_registration(): - print request.json if request.method == 'POST': # santinize user input when registration - username=bleach.clean(request.json.get('username')) - password=request.json.get('password') - fullname=bleach.clean(request.json.get('fullname')) - age=request.json.get('age') - - if username is None or password is None or fullname is None: - print 'missing required field' - abort(400) + fullname = bleach.clean(request.json.get('fullname')) + age = bleach.clean(request.json.get('age')) + username = bleach.clean(request.json.get('username')) + password = bleach.clean(request.json.get('password')) + + if not fullname or not age or not username or not password: + if not fullname: + text = 'Full Name' + elif not age: + text = 'Age' + elif not username: + text = 'Username' + elif not password: + text = 'Password' + return jsonify({'status': False, 'error': text + ' is required'}) if session.query(User).filter_by(username=username).first() is not None: return jsonify({'status': False, 'error': 'User already exists!'}), 200 diff --git a/src/webapp/src/App.js b/src/webapp/src/App.js index cac65cd..81fb5cb 100644 --- a/src/webapp/src/App.js +++ b/src/webapp/src/App.js @@ -3,6 +3,7 @@ import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; import './App.css'; import Home from './components/Home'; import Login from './components/Login'; +import Signup from './components/Signup'; class App extends Component { render() { @@ -14,6 +15,7 @@ class App extends Component {
  • Home Login + Register User
  • @@ -21,6 +23,7 @@ class App extends Component { + diff --git a/src/webapp/src/components/Signup.js b/src/webapp/src/components/Signup.js new file mode 100644 index 0000000..11d5784 --- /dev/null +++ b/src/webapp/src/components/Signup.js @@ -0,0 +1,136 @@ +import React, { Component } from 'react'; +import ajax_post from '../utils/ajax_post'; +import API_Endpoints from '../utils/API_Endpoints'; + +class Signup extends Component { + constructor(props) { + super(props); + this.state = { + fullname: '', + age: '', + username: '', + password: '', + passwordAgain: '', + error: '' + }; + } + + handleChange(key, value) { + this.setState({ + [key]: value + }); + } + + handleSignup() { + const { fullname, age, username, password, passwordAgain } = this.state; + if (!fullname.trim()) { + this.setState({ + error: 'Full Name is required' + }); + return; + } + if (!age || isNaN(age)) { + this.setState({ + error: !age ? 'Age is required' : 'Age should be an number' + }); + return; + } + if (!username.trim()) { + this.setState({ + error: 'Username is required' + }); + return; + } + if (!password.trim()) { + this.setState({ + error: 'Password is required' + }); + return; + } + if (password !== passwordAgain) { + this.setState({ + password: '', + passwordAgain: '', + error: "Password confirmation doens't match" + }); + return; + } + ajax_post( + API_Endpoints.register_user, + { fullname, age, username, password }, + data => { + if (data.status) { + } else { + this.setState({ error: 'Username or password incorrect' }); + } + } + ); + } + + render() { + const { + fullname, + age, + username, + password, + passwordAgain, + error + } = this.state; + return ( +
    + this.handleChange(e.target.name, e.target.value)} + value={fullname} + /> + this.handleChange(e.target.name, e.target.value)} + value={age} + /> + this.handleChange(e.target.name, e.target.value)} + value={username} + /> + this.handleChange(e.target.name, e.target.value)} + value={password} + /> + this.handleChange(e.target.name, e.target.value)} + value={passwordAgain} + /> + + {!!error ?

    {error}

    : ''} +
    + ); + } +} + +export default Signup; From b9303b11973e392b7d225809dde59f9aeed81c14 Mon Sep 17 00:00:00 2001 From: Liu Chao Date: Sun, 25 Feb 2018 17:30:07 +0800 Subject: [PATCH 24/54] Use bootstrap style --- src/webapp/package.json | 5 + src/webapp/src/App.css | 28 ---- src/webapp/src/App.js | 41 +++-- src/webapp/src/components/Home.js | 18 ++- src/webapp/src/components/Login.js | 143 +++++++++++------ src/webapp/src/components/Signup.js | 235 +++++++++++++++------------- src/webapp/src/index.css | 6 +- src/webapp/src/index.js | 2 + src/webapp/yarn.lock | 99 +++++++++++- 9 files changed, 366 insertions(+), 211 deletions(-) delete mode 100644 src/webapp/src/App.css diff --git a/src/webapp/package.json b/src/webapp/package.json index 4a4c124..f942a72 100644 --- a/src/webapp/package.json +++ b/src/webapp/package.json @@ -3,8 +3,13 @@ "version": "0.1.0", "private": true, "dependencies": { + "bootstrap": "3", + "font-awesome": "^4.7.0", "react": "^16.2.0", + "react-bootstrap": "^0.32.1", "react-dom": "^16.2.0", + "react-fontawesome": "^1.6.1", + "react-router-bootstrap": "^0.24.4", "react-router-dom": "^4.2.2", "react-scripts": "1.1.1" }, diff --git a/src/webapp/src/App.css b/src/webapp/src/App.css deleted file mode 100644 index c5c6e8a..0000000 --- a/src/webapp/src/App.css +++ /dev/null @@ -1,28 +0,0 @@ -.App { - text-align: center; -} - -.App-logo { - animation: App-logo-spin infinite 20s linear; - height: 80px; -} - -.App-header { - background-color: #222; - height: 150px; - padding: 20px; - color: white; -} - -.App-title { - font-size: 1.5em; -} - -.App-intro { - font-size: large; -} - -@keyframes App-logo-spin { - from { transform: rotate(0deg); } - to { transform: rotate(360deg); } -} diff --git a/src/webapp/src/App.js b/src/webapp/src/App.js index 81fb5cb..65eb59c 100644 --- a/src/webapp/src/App.js +++ b/src/webapp/src/App.js @@ -1,29 +1,42 @@ import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; -import './App.css'; import Home from './components/Home'; import Login from './components/Login'; import Signup from './components/Signup'; +import { Alert, Navbar, Nav, NavItem, Grid, Row, Col } from 'react-bootstrap'; +import { LinkContainer } from 'react-router-bootstrap'; class App extends Component { render() { return ( -
    +
    -
      -
    • - Home - Login - Register User -
    • -
    + + + + Home + + + + -
    - - - - + + + + + + + + +
    diff --git a/src/webapp/src/components/Home.js b/src/webapp/src/components/Home.js index 8680db8..cef48a0 100644 --- a/src/webapp/src/components/Home.js +++ b/src/webapp/src/components/Home.js @@ -1,6 +1,7 @@ import React, { Component } from 'react'; import ajax_get from '../utils/ajax_get'; import API_Endpoints from '../utils/API_Endpoints'; +import { PageHeader, Panel } from 'react-bootstrap'; class Home extends Component { constructor(props) { @@ -22,16 +23,19 @@ class Home extends Component { render() { const members = this.state.members.map(name => ( -
    -

    {name}

    -
    +
      +
    • {name}
    • +
    )); return (
    -
    -

    Welcome to CS5331 - Group WLKB

    -
    -
    Team Members: {members}
    + Welcome to CS5331 - Group WLKB + + + Team Members + + {members} +
    ); } diff --git a/src/webapp/src/components/Login.js b/src/webapp/src/components/Login.js index 71fdebd..17f7e91 100644 --- a/src/webapp/src/components/Login.js +++ b/src/webapp/src/components/Login.js @@ -1,64 +1,119 @@ import React, { Component } from 'react'; import ajax_post from '../utils/ajax_post'; import API_Endpoints from '../utils/API_Endpoints'; +import { + Alert, + Form, + FormGroup, + FormControl, + Button, + Col, + ControlLabel, + Panel +} from 'react-bootstrap'; +import FontAwesome from 'react-fontawesome'; class Login extends Component { constructor(props) { super(props); this.state = { - username: '', - password: '', - error: '' + error: '', + message: '', + isLoading: false }; } - handleChange(key, value) { - this.setState({ - [key]: value - }); + setError(error) { + this.setState({ error }); } - handleLogin() { - const { username, password } = this.state; - ajax_post(API_Endpoints.authenticate_user, { username, password }, data => { - if (data.status) { - this.setState({ members: data.result }); - } else { - this.setState({ error: 'Username or password incorrect' }); - } - }); + setMessage(message) { + this.setState({ message }); + } + + handleLogin(e) { + e.preventDefault(); + const username = (this.usernameField.value || '').trim(); + const password = (this.passwordField.value || '').trim(); + + if (!username) { + this.setError('Username is required'); + } else if (!password) { + this.setError('Password is required'); + } else { + this.setState({ + isLoading: true + }); + ajax_post( + API_Endpoints.authenticate_user, + { username, password }, + data => { + this.setState({ + isLoading: false + }); + if (data.status) { + this.setMessage('Login successfully'); + } else { + this.passwordField.value = ''; + this.passwordField.focus(); + this.setState({ error: 'Invalid username or password' }); + } + } + ); + } } render() { - const { username, password } = this.state; + const { error, message, isLoading } = this.state; return ( -
    - this.handleChange(e.target.name, e.target.value)} - value={username} - /> - this.handleChange(e.target.name, e.target.value)} - value={password} - /> - -
    + + + Log In + + +
    + {error ? ( + {error} + ) : message ? ( + {message} + ) : ( + '' + )} + + + Username + + + (this.usernameField = ref)} + /> + + + + + Password + + + (this.passwordField = ref)} + /> + + + + + + + +
    +
    +
    ); } } diff --git a/src/webapp/src/components/Signup.js b/src/webapp/src/components/Signup.js index 11d5784..9d2d679 100644 --- a/src/webapp/src/components/Signup.js +++ b/src/webapp/src/components/Signup.js @@ -1,134 +1,147 @@ import React, { Component } from 'react'; import ajax_post from '../utils/ajax_post'; import API_Endpoints from '../utils/API_Endpoints'; +import { + Alert, + Form, + FormGroup, + FormControl, + Button, + Col, + ControlLabel, + Panel +} from 'react-bootstrap'; +import FontAwesome from 'react-fontawesome'; class Signup extends Component { constructor(props) { super(props); this.state = { - fullname: '', - age: '', - username: '', - password: '', - passwordAgain: '', - error: '' + error: '', + message: '', + isLoading: false }; } - handleChange(key, value) { - this.setState({ - [key]: value - }); + setError(error) { + this.setState({ error }); } - handleSignup() { - const { fullname, age, username, password, passwordAgain } = this.state; - if (!fullname.trim()) { - this.setState({ - error: 'Full Name is required' - }); - return; - } - if (!age || isNaN(age)) { - this.setState({ - error: !age ? 'Age is required' : 'Age should be an number' - }); - return; - } - if (!username.trim()) { - this.setState({ - error: 'Username is required' - }); - return; - } - if (!password.trim()) { - this.setState({ - error: 'Password is required' - }); - return; - } - if (password !== passwordAgain) { + setMessage(message) { + this.setState({ message }); + } + + handleSignup(e) { + e.preventDefault(); + const fullname = (this.fullnameField.value || '').trim(); + const age = (this.ageField.value || '').trim(); + const username = (this.usernameField.value || '').trim(); + const password = (this.passwordField.value || '').trim(); + + if (!fullname) { + this.setError('Full Name is required'); + } else if (!age) { + this.setError('Age is required'); + } else if (!username) { + this.setError('Username is required'); + } else if (!password) { + this.setError('Password is required'); + } else { this.setState({ - password: '', - passwordAgain: '', - error: "Password confirmation doens't match" + isLoading: false }); - return; - } - ajax_post( - API_Endpoints.register_user, - { fullname, age, username, password }, - data => { - if (data.status) { - } else { - this.setState({ error: 'Username or password incorrect' }); + ajax_post( + API_Endpoints.register_user, + { fullname, age, username, password }, + data => { + this.setState({ + isLoading: false + }); + if (data.status) { + this.setMessage('Account created successfully'); + } else { + this.setError(data.error); + } } - } - ); + ); + } } render() { - const { - fullname, - age, - username, - password, - passwordAgain, - error - } = this.state; + const { error, message, isLoading } = this.state; return ( -
    - this.handleChange(e.target.name, e.target.value)} - value={fullname} - /> - this.handleChange(e.target.name, e.target.value)} - value={age} - /> - this.handleChange(e.target.name, e.target.value)} - value={username} - /> - this.handleChange(e.target.name, e.target.value)} - value={password} - /> - this.handleChange(e.target.name, e.target.value)} - value={passwordAgain} - /> - - {!!error ?

    {error}

    : ''} -
    + + + Sign Up + + +
    + {error ? ( + {error} + ) : message ? ( + {message} + ) : ( + '' + )} + + + Full Name + + + (this.fullnameField = ref)} + /> + + + + + Age + + + (this.ageField = ref)} + /> + + + + + Username + + + (this.usernameField = ref)} + /> + + + + + Password + + + (this.passwordField = ref)} + /> + + + + + + + +
    +
    +
    ); } } diff --git a/src/webapp/src/index.css b/src/webapp/src/index.css index b4cc725..2037faa 100644 --- a/src/webapp/src/index.css +++ b/src/webapp/src/index.css @@ -1,5 +1,3 @@ -body { - margin: 0; - padding: 0; - font-family: sans-serif; +.fa { + margin-right: 5px; } diff --git a/src/webapp/src/index.js b/src/webapp/src/index.js index fae3e35..b9e91ad 100644 --- a/src/webapp/src/index.js +++ b/src/webapp/src/index.js @@ -1,6 +1,8 @@ import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; +import 'bootstrap/dist/css/bootstrap.min.css'; +import 'font-awesome/css/font-awesome.min.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; diff --git a/src/webapp/yarn.lock b/src/webapp/yarn.lock index d912529..dac6c8f 100644 --- a/src/webapp/yarn.lock +++ b/src/webapp/yarn.lock @@ -918,7 +918,7 @@ babel-register@^6.26.0: mkdirp "^0.5.1" source-map-support "^0.4.15" -babel-runtime@6.26.0, babel-runtime@^6.18.0, babel-runtime@^6.22.0, babel-runtime@^6.26.0: +babel-runtime@6.26.0, babel-runtime@^6.11.6, babel-runtime@^6.18.0, babel-runtime@^6.22.0, babel-runtime@^6.26.0: version "6.26.0" resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.26.0.tgz#965c7058668e82b55d7bfe04ff2337bc8b5647fe" dependencies: @@ -1054,6 +1054,10 @@ boom@5.x.x: dependencies: hoek "4.x.x" +bootstrap@3: + version "3.3.7" + resolved "https://registry.yarnpkg.com/bootstrap/-/bootstrap-3.3.7.tgz#5a389394549f23330875a3b150656574f8a9eb71" + boxen@^1.2.1: version "1.3.0" resolved "https://registry.yarnpkg.com/boxen/-/boxen-1.3.0.tgz#55c6c39a8ba58d9c61ad22cd877532deb665a20b" @@ -1277,6 +1281,10 @@ center-align@^0.1.1: align-text "^0.1.3" lazy-cache "^1.0.3" +chain-function@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/chain-function/-/chain-function-1.0.0.tgz#0d4ab37e7e18ead0bdc47b920764118ce58733dc" + chalk@1.1.3, chalk@^1.1.3: version "1.1.3" resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98" @@ -1335,6 +1343,10 @@ clap@^1.0.9: dependencies: chalk "^1.1.3" +classnames@^2.2.5: + version "2.2.5" + resolved "https://registry.yarnpkg.com/classnames/-/classnames-2.2.5.tgz#fb3801d453467649ef3603c7d61a02bd129bde6d" + clean-css@4.1.x: version "4.1.9" resolved "https://registry.yarnpkg.com/clean-css/-/clean-css-4.1.9.tgz#35cee8ae7687a49b98034f70de00c4edd3826301" @@ -1915,6 +1927,10 @@ dom-converter@~0.1: dependencies: utila "~0.3" +dom-helpers@^3.2.0, dom-helpers@^3.2.1: + version "3.3.1" + resolved "https://registry.yarnpkg.com/dom-helpers/-/dom-helpers-3.3.1.tgz#fc1a4e15ffdf60ddde03a480a9c0fece821dd4a6" + dom-serializer@0: version "0.1.0" resolved "https://registry.yarnpkg.com/dom-serializer/-/dom-serializer-0.1.0.tgz#073c697546ce0780ce23be4a28e293e40bc30c82" @@ -2600,6 +2616,10 @@ flatten@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/flatten/-/flatten-1.0.2.tgz#dae46a9d78fbe25292258cc1e780a41d95c03782" +font-awesome@^4.7.0: + version "4.7.0" + resolved "https://registry.yarnpkg.com/font-awesome/-/font-awesome-4.7.0.tgz#8fa8cf0411a1a31afd07b06d2902bb9fc815a133" + for-in@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80" @@ -3191,7 +3211,7 @@ interpret@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.1.0.tgz#7ed1b1410c6a0e0f78cf95d3b8440c63f78b8614" -invariant@^2.2.1, invariant@^2.2.2: +invariant@^2.1.0, invariant@^2.2.1, invariant@^2.2.2: version "2.2.3" resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.3.tgz#1a827dfde7dcbd7c323f0ca826be8fa7c5e9d688" dependencies: @@ -3838,6 +3858,10 @@ jsx-ast-utils@^2.0.0: dependencies: array-includes "^3.0.3" +keycode@^2.1.2: + version "2.1.9" + resolved "https://registry.yarnpkg.com/keycode/-/keycode-2.1.9.tgz#964a23c54e4889405b4861a5c9f0480d45141dfa" + killable@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/killable/-/killable-1.0.0.tgz#da8b84bd47de5395878f95d64d02f2449fe05e6b" @@ -5005,7 +5029,13 @@ promise@^7.1.1: dependencies: asap "~2.0.3" -prop-types@^15.5.10, prop-types@^15.5.4, prop-types@^15.6.0: +prop-types-extra@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/prop-types-extra/-/prop-types-extra-1.0.1.tgz#a57bd4810e82d27a3ff4317ecc1b4ad005f79a82" + dependencies: + warning "^3.0.0" + +prop-types@^15.5.10, prop-types@^15.5.4, prop-types@^15.5.6, prop-types@^15.5.8, prop-types@^15.6.0: version "15.6.0" resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.6.0.tgz#ceaf083022fc46b4a35f69e13ef75aed0d639856" dependencies: @@ -5129,6 +5159,23 @@ rc@^1.0.1, rc@^1.1.6, rc@^1.1.7: minimist "^1.2.0" strip-json-comments "~2.0.1" +react-bootstrap@^0.32.1: + version "0.32.1" + resolved "https://registry.yarnpkg.com/react-bootstrap/-/react-bootstrap-0.32.1.tgz#60624c1b48a39d773ef6cce6421a4f33ecc166bb" + dependencies: + babel-runtime "^6.11.6" + classnames "^2.2.5" + dom-helpers "^3.2.0" + invariant "^2.2.1" + keycode "^2.1.2" + prop-types "^15.5.10" + prop-types-extra "^1.0.1" + react-overlays "^0.8.0" + react-prop-types "^0.4.0" + react-transition-group "^2.0.0" + uncontrollable "^4.1.0" + warning "^3.0.0" + react-dev-utils@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/react-dev-utils/-/react-dev-utils-5.0.0.tgz#425ac7c9c40c2603bc4f7ab8836c1406e96bb473" @@ -5165,6 +5212,35 @@ react-error-overlay@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/react-error-overlay/-/react-error-overlay-4.0.0.tgz#d198408a85b4070937a98667f500c832f86bd5d4" +react-fontawesome@^1.6.1: + version "1.6.1" + resolved "https://registry.yarnpkg.com/react-fontawesome/-/react-fontawesome-1.6.1.tgz#eddce17e7dc731aa09fd4a186688a61793a16c5c" + dependencies: + prop-types "^15.5.6" + +react-overlays@^0.8.0: + version "0.8.3" + resolved "https://registry.yarnpkg.com/react-overlays/-/react-overlays-0.8.3.tgz#fad65eea5b24301cca192a169f5dddb0b20d3ac5" + dependencies: + classnames "^2.2.5" + dom-helpers "^3.2.1" + prop-types "^15.5.10" + prop-types-extra "^1.0.1" + react-transition-group "^2.2.0" + warning "^3.0.0" + +react-prop-types@^0.4.0: + version "0.4.0" + resolved "https://registry.yarnpkg.com/react-prop-types/-/react-prop-types-0.4.0.tgz#f99b0bfb4006929c9af2051e7c1414a5c75b93d0" + dependencies: + warning "^3.0.0" + +react-router-bootstrap@^0.24.4: + version "0.24.4" + resolved "https://registry.yarnpkg.com/react-router-bootstrap/-/react-router-bootstrap-0.24.4.tgz#6e89481d8a8979649a0dd4535e4a68df4a3d0b12" + dependencies: + prop-types "^15.5.10" + react-router-dom@^4.2.2: version "4.2.2" resolved "https://registry.yarnpkg.com/react-router-dom/-/react-router-dom-4.2.2.tgz#c8a81df3adc58bba8a76782e946cbd4eae649b8d" @@ -5232,6 +5308,17 @@ react-scripts@1.1.1: optionalDependencies: fsevents "^1.1.3" +react-transition-group@^2.0.0, react-transition-group@^2.2.0: + version "2.2.1" + resolved "https://registry.yarnpkg.com/react-transition-group/-/react-transition-group-2.2.1.tgz#e9fb677b79e6455fd391b03823afe84849df4a10" + dependencies: + chain-function "^1.0.0" + classnames "^2.2.5" + dom-helpers "^3.2.0" + loose-envify "^1.3.1" + prop-types "^15.5.8" + warning "^3.0.0" + react@^16.2.0: version "16.2.0" resolved "https://registry.yarnpkg.com/react/-/react-16.2.0.tgz#a31bd2dab89bff65d42134fa187f24d054c273ba" @@ -6207,6 +6294,12 @@ uid-number@^0.0.6: version "0.0.6" resolved "https://registry.yarnpkg.com/uid-number/-/uid-number-0.0.6.tgz#0ea10e8035e8eb5b8e4449f06da1c730663baa81" +uncontrollable@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/uncontrollable/-/uncontrollable-4.1.0.tgz#e0358291252e1865222d90939b19f2f49f81c1a9" + dependencies: + invariant "^2.1.0" + uniq@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/uniq/-/uniq-1.0.1.tgz#b31c5ae8254844a3a8281541ce2b04b865a734ff" From cf107b48512cb968c6c83939839cd7a05d8575a2 Mon Sep 17 00:00:00 2001 From: Liu Chao Date: Sun, 25 Feb 2018 18:18:29 +0800 Subject: [PATCH 25/54] Render public diaries --- src/webapp/src/App.js | 2 +- src/webapp/src/components/Diaries.js | 32 +++++++++++ src/webapp/src/components/Diary.js | 10 ++++ src/webapp/src/components/Home.js | 80 +++++++++++++++++++++++++--- src/webapp/src/utils/ajax_get.js | 2 +- src/webapp/src/utils/ajax_post.js | 2 +- 6 files changed, 118 insertions(+), 10 deletions(-) create mode 100644 src/webapp/src/components/Diaries.js create mode 100644 src/webapp/src/components/Diary.js diff --git a/src/webapp/src/App.js b/src/webapp/src/App.js index 65eb59c..ae1e768 100644 --- a/src/webapp/src/App.js +++ b/src/webapp/src/App.js @@ -3,7 +3,7 @@ import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; import Home from './components/Home'; import Login from './components/Login'; import Signup from './components/Signup'; -import { Alert, Navbar, Nav, NavItem, Grid, Row, Col } from 'react-bootstrap'; +import { Navbar, Nav, NavItem, Grid, Row, Col } from 'react-bootstrap'; import { LinkContainer } from 'react-router-bootstrap'; class App extends Component { diff --git a/src/webapp/src/components/Diaries.js b/src/webapp/src/components/Diaries.js new file mode 100644 index 0000000..271d13c --- /dev/null +++ b/src/webapp/src/components/Diaries.js @@ -0,0 +1,32 @@ +import React, { Component } from 'react'; +import FontAwesome from 'react-fontawesome'; +import Diary from './Diary'; + +class Diaries extends Component { + render() { + const { isLoading, diaries } = this.props; + if (isLoading) { + return ( + + Loading... + + ); + } else if (diaries.length) { + return ( +
      + {diaries.map(diary => { + return ( +
    • + +
    • + ); + })} +
    + ); + } else { + return No data found; + } + } +} + +export default Diaries; diff --git a/src/webapp/src/components/Diary.js b/src/webapp/src/components/Diary.js new file mode 100644 index 0000000..4bcc27c --- /dev/null +++ b/src/webapp/src/components/Diary.js @@ -0,0 +1,10 @@ +import React, { Component } from 'react'; + +class Diary extends Component { + render() { + const { diary } = this.props; + return 'hello world'; + } +} + +export default Diary; diff --git a/src/webapp/src/components/Home.js b/src/webapp/src/components/Home.js index cef48a0..4b4d285 100644 --- a/src/webapp/src/components/Home.js +++ b/src/webapp/src/components/Home.js @@ -2,31 +2,75 @@ import React, { Component } from 'react'; import ajax_get from '../utils/ajax_get'; import API_Endpoints from '../utils/API_Endpoints'; import { PageHeader, Panel } from 'react-bootstrap'; +import Diaries from './Diaries.js'; +import FontAwesome from 'react-fontawesome'; class Home extends Component { constructor(props) { super(props); - this.state = { members: [] }; + this.state = { + isLoadingMembers: true, + members: [], + isLoadingPublicDiaries: true, + publicDiaries: [] + }; } componentDidMount() { this.getMembers(); + this.getPublicDiaries(); } getMembers() { + this.setState({ + isLoadingMembers: true + }); ajax_get(API_Endpoints.get_members, data => { + this.setState({ + isLoadingMembers: false + }); if (data.status) { this.setState({ members: data.result }); } }); } + renderMembers() { + const { isLoadingMembers, members } = this.state; + if (isLoadingMembers) { + return ( + + Loading... + + ); + } else { + return ( +
      + {members.map(name => { + return
    • {name}
    • ; + })} +
    + ); + } + } + + getPublicDiaries() { + this.setState({ + isLoadingPublicDiaries: true + }); + ajax_get(API_Endpoints.get_public_diaries, data => { + this.setState({ + isLoadingPublicDiaries: false + }); + if (data.status) { + this.setState({ publicDiaries: data.result }); + } + }); + } + render() { - const members = this.state.members.map(name => ( -
      -
    • {name}
    • -
    - )); + const { isLoadingPublicDiaries, publicDiaries } = this.state; + return (
    Welcome to CS5331 - Group WLKB @@ -34,7 +78,29 @@ class Home extends Component { Team Members - {members} + {this.renderMembers()} + + + + Public Diaries + + + + + + + + My Diaries + + + +
    ); diff --git a/src/webapp/src/utils/ajax_get.js b/src/webapp/src/utils/ajax_get.js index b93a41c..1efa1c2 100644 --- a/src/webapp/src/utils/ajax_get.js +++ b/src/webapp/src/utils/ajax_get.js @@ -1,7 +1,7 @@ const ajax_get = function(url, callback) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { - if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { + if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { console.log('responseText:' + xmlhttp.responseText); try { var data = JSON.parse(xmlhttp.responseText); diff --git a/src/webapp/src/utils/ajax_post.js b/src/webapp/src/utils/ajax_post.js index b84fcb4..7606b63 100644 --- a/src/webapp/src/utils/ajax_post.js +++ b/src/webapp/src/utils/ajax_post.js @@ -1,7 +1,7 @@ const ajax_post = function(url, data = {}, callback) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { - if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { + if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { console.log('responseText:' + xmlhttp.responseText); try { var data = JSON.parse(xmlhttp.responseText); From a6f05369c8208c90ca081e05afa6a4c21ebb0458 Mon Sep 17 00:00:00 2001 From: Liu Chao Date: Sun, 25 Feb 2018 22:01:45 +0800 Subject: [PATCH 26/54] Use react-redux --- src/webapp/package.json | 7 +- src/webapp/src/actions.js | 69 ++++++++++++ src/webapp/src/components/Home.js | 83 +++++--------- src/webapp/src/components/Login.js | 14 +-- src/webapp/src/components/Signup.js | 168 +++++++++++++++------------- src/webapp/src/configureStore.js | 13 +++ src/webapp/src/index.js | 18 ++- src/webapp/src/reducers.js | 57 ++++++++++ src/webapp/src/utils/ajax_get.js | 20 +--- src/webapp/src/utils/ajax_post.js | 26 ++--- src/webapp/yarn.lock | 57 +++++++++- 11 files changed, 349 insertions(+), 183 deletions(-) create mode 100644 src/webapp/src/actions.js create mode 100644 src/webapp/src/configureStore.js create mode 100644 src/webapp/src/reducers.js diff --git a/src/webapp/package.json b/src/webapp/package.json index f942a72..0886ca5 100644 --- a/src/webapp/package.json +++ b/src/webapp/package.json @@ -4,14 +4,19 @@ "private": true, "dependencies": { "bootstrap": "3", + "cross-fetch": "^1.1.1", "font-awesome": "^4.7.0", "react": "^16.2.0", "react-bootstrap": "^0.32.1", "react-dom": "^16.2.0", "react-fontawesome": "^1.6.1", + "react-redux": "^5.0.7", "react-router-bootstrap": "^0.24.4", "react-router-dom": "^4.2.2", - "react-scripts": "1.1.1" + "react-scripts": "1.1.1", + "redux": "^3.7.2", + "redux-logger": "^3.0.6", + "redux-thunk": "^2.2.0" }, "scripts": { "start": "react-scripts start", diff --git a/src/webapp/src/actions.js b/src/webapp/src/actions.js new file mode 100644 index 0000000..57ba8e8 --- /dev/null +++ b/src/webapp/src/actions.js @@ -0,0 +1,69 @@ +import ajax_get from './utils/ajax_get'; +import API_Endpoints from './utils/API_Endpoints'; + +export const REQUEST_MEMBERS = 'REQUEST_MEMBERS'; +export const RECEIVE_MEMBERS = 'RECEIVE_MEMBERS'; +export const REQUEST_PUBLIC_DIARIES = 'REQUEST_PUBLIC_DIARIES'; +export const RECEIVE_PUBLIC_DIARIES = 'RECEIVE_PUBLIC_DIARIES'; + +function requestMembers() { + return { + type: REQUEST_MEMBERS + }; +} + +function receiveMembers(json) { + return { + type: RECEIVE_MEMBERS, + members: json.result + }; +} + +function requestPublicDiaires() { + return { + type: REQUEST_PUBLIC_DIARIES + }; +} + +function receivePublicDiaries(json) { + return { + type: RECEIVE_PUBLIC_DIARIES, + publicDiaries: json.result + }; +} + +function requestItems(type) { + switch (type) { + case 'members': + return requestMembers(); + case 'public-diaries': + return requestPublicDiaires(); + } +} + +function receiveItems(type, json) { + switch (type) { + case 'members': + return receiveMembers(json); + case 'public-diaries': + return receivePublicDiaries(json); + } +} + +function getUrl(type) { + switch (type) { + case 'members': + return API_Endpoints.get_members; + case 'public-diaries': + return API_Endpoints.get_public_diaries; + } +} + +export function fetchItems(type) { + return dispatch => { + dispatch(requestItems(type)); + return ajax_get(getUrl(type)) + .then(response => response.json()) + .then(json => dispatch(receiveItems(type, json))); + }; +} diff --git a/src/webapp/src/components/Home.js b/src/webapp/src/components/Home.js index 4b4d285..720f602 100644 --- a/src/webapp/src/components/Home.js +++ b/src/webapp/src/components/Home.js @@ -4,39 +4,18 @@ import API_Endpoints from '../utils/API_Endpoints'; import { PageHeader, Panel } from 'react-bootstrap'; import Diaries from './Diaries.js'; import FontAwesome from 'react-fontawesome'; +import { connect } from 'react-redux'; +import { fetchItems } from '../actions'; class Home extends Component { - constructor(props) { - super(props); - this.state = { - isLoadingMembers: true, - members: [], - isLoadingPublicDiaries: true, - publicDiaries: [] - }; - } - componentDidMount() { - this.getMembers(); - this.getPublicDiaries(); - } - - getMembers() { - this.setState({ - isLoadingMembers: true - }); - ajax_get(API_Endpoints.get_members, data => { - this.setState({ - isLoadingMembers: false - }); - if (data.status) { - this.setState({ members: data.result }); - } - }); + const { dispatch } = this.props; + dispatch(fetchItems('members')); + dispatch(fetchItems('public-diaries')); } renderMembers() { - const { isLoadingMembers, members } = this.state; + const { isLoadingMembers, members } = this.props; if (isLoadingMembers) { return ( @@ -54,22 +33,8 @@ class Home extends Component { } } - getPublicDiaries() { - this.setState({ - isLoadingPublicDiaries: true - }); - ajax_get(API_Endpoints.get_public_diaries, data => { - this.setState({ - isLoadingPublicDiaries: false - }); - if (data.status) { - this.setState({ publicDiaries: data.result }); - } - }); - } - render() { - const { isLoadingPublicDiaries, publicDiaries } = this.state; + const { isLoadingPublicDiaries, publicDiaries } = this.props; return (
    @@ -91,20 +56,30 @@ class Home extends Component { /> - - - My Diaries - - - - -
    ); } } -export default Home; +function mapStateToProps(state) { + const { members: allMembers, publicDiaries: allPublicDiaries } = state; + const { isFetching: isLoadingMembers, items: members } = allMembers || { + isFetching: true, + items: [] + }; + const { + isFetching: isLoadingPublicDiaries, + items: publicDiaries + } = allPublicDiaries || { + isFetching: true, + items: [] + }; + return { + isLoadingMembers, + members, + isLoadingPublicDiaries, + publicDiaries + }; +} + +export default connect(mapStateToProps)(Home); diff --git a/src/webapp/src/components/Login.js b/src/webapp/src/components/Login.js index 17f7e91..1c6b190 100644 --- a/src/webapp/src/components/Login.js +++ b/src/webapp/src/components/Login.js @@ -71,14 +71,14 @@ class Login extends Component { Log In + {error ? ( + {error} + ) : message ? ( + {message} + ) : ( + '' + )}
    - {error ? ( - {error} - ) : message ? ( - {message} - ) : ( - '' - )} Username diff --git a/src/webapp/src/components/Signup.js b/src/webapp/src/components/Signup.js index 9d2d679..9dc76cd 100644 --- a/src/webapp/src/components/Signup.js +++ b/src/webapp/src/components/Signup.js @@ -48,98 +48,106 @@ class Signup extends Component { this.setError('Password is required'); } else { this.setState({ - isLoading: false + isLoading: true }); - ajax_post( - API_Endpoints.register_user, - { fullname, age, username, password }, - data => { - this.setState({ - isLoading: false - }); - if (data.status) { - this.setMessage('Account created successfully'); - } else { - this.setError(data.error); - } + ajax_post(API_Endpoints.register_user, { + fullname, + age, + username, + password + }).then(data => { + this.setState({ + isLoading: false + }); + if (data.status) { + this.setMessage('Account created successfully'); + } else { + this.setError(data.error); } - ); + }); } } + renderForm() { + const { isLoading } = this.state; + return ( + + + + Full Name + + + (this.fullnameField = ref)} + /> + + + + + Age + + + (this.ageField = ref)} + /> + + + + + Username + + + (this.usernameField = ref)} + /> + + + + + Password + + + (this.passwordField = ref)} + /> + + + + + + + + + ); + } + render() { - const { error, message, isLoading } = this.state; + const { error, message } = this.state; return ( Sign Up -
    - {error ? ( - {error} - ) : message ? ( - {message} - ) : ( - '' - )} - - - Full Name - - - (this.fullnameField = ref)} - /> - - - - - Age - - - (this.ageField = ref)} - /> - - - - - Username - - - (this.usernameField = ref)} - /> - - - - - Password - - - (this.passwordField = ref)} - /> - - - - - - - -
    + {error ? ( + {error} + ) : message ? ( + {message} + ) : ( + '' + )} + {!message ? this.renderForm() : ''}
    ); diff --git a/src/webapp/src/configureStore.js b/src/webapp/src/configureStore.js new file mode 100644 index 0000000..243c016 --- /dev/null +++ b/src/webapp/src/configureStore.js @@ -0,0 +1,13 @@ +import { createStore, applyMiddleware } from 'redux'; +import thunkMiddleware from 'redux-thunk'; +import { createLogger } from 'redux-logger'; +import rootReducer from './reducers'; +const loggerMiddleware = createLogger(); + +export default function configureStore(preloadedState) { + return createStore( + rootReducer, + preloadedState, + applyMiddleware(thunkMiddleware, loggerMiddleware) + ); +} diff --git a/src/webapp/src/index.js b/src/webapp/src/index.js index b9e91ad..f11dfe6 100644 --- a/src/webapp/src/index.js +++ b/src/webapp/src/index.js @@ -1,10 +1,22 @@ import React from 'react'; import ReactDOM from 'react-dom'; +import App from './App'; +import { createStore } from 'redux'; +import { Provider } from 'react-redux'; +import configureStore from './configureStore'; +import registerServiceWorker from './registerServiceWorker'; + import './index.css'; import 'bootstrap/dist/css/bootstrap.min.css'; import 'font-awesome/css/font-awesome.min.css'; -import App from './App'; -import registerServiceWorker from './registerServiceWorker'; -ReactDOM.render(, document.getElementById('root')); +const store = configureStore(); + +ReactDOM.render( + + + , + document.getElementById('root') +); + registerServiceWorker(); diff --git a/src/webapp/src/reducers.js b/src/webapp/src/reducers.js new file mode 100644 index 0000000..0987714 --- /dev/null +++ b/src/webapp/src/reducers.js @@ -0,0 +1,57 @@ +import { combineReducers } from 'redux'; +import { + REQUEST_MEMBERS, + RECEIVE_MEMBERS, + REQUEST_PUBLIC_DIARIES, + RECEIVE_PUBLIC_DIARIES +} from './actions'; + +function members( + state = { + isFetching: false, + items: [] + }, + action +) { + switch (action.type) { + case REQUEST_MEMBERS: + return Object.assign({}, state, { + isFetching: true + }); + case RECEIVE_MEMBERS: + return Object.assign({}, state, { + isFetching: false, + items: action.members + }); + default: + return state; + } +} + +function publicDiaries( + state = { + isFetching: false, + items: [] + }, + action +) { + switch (action.type) { + case REQUEST_PUBLIC_DIARIES: + return Object.assign({}, state, { + isFetching: true + }); + case RECEIVE_PUBLIC_DIARIES: + return Object.assign({}, state, { + isFetching: false, + items: action.publicDiaries + }); + default: + return state; + } +} + +const rootReducer = combineReducers({ + members, + publicDiaries +}); +export default rootReducer; diff --git a/src/webapp/src/utils/ajax_get.js b/src/webapp/src/utils/ajax_get.js index 1efa1c2..d39dcfc 100644 --- a/src/webapp/src/utils/ajax_get.js +++ b/src/webapp/src/utils/ajax_get.js @@ -1,21 +1,7 @@ -const ajax_get = function(url, callback) { - var xmlhttp = new XMLHttpRequest(); - xmlhttp.onreadystatechange = function() { - if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { - console.log('responseText:' + xmlhttp.responseText); - try { - var data = JSON.parse(xmlhttp.responseText); - } catch (err) { - console.log(err.message + ' in ' + xmlhttp.responseText); - return; - } - callback(data); - } - }; +import fetch from 'cross-fetch'; - xmlhttp.open('GET', url, true); - xmlhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); - xmlhttp.send(); +const ajax_get = function(url) { + return fetch(url); }; export default ajax_get; diff --git a/src/webapp/src/utils/ajax_post.js b/src/webapp/src/utils/ajax_post.js index 7606b63..376303d 100644 --- a/src/webapp/src/utils/ajax_post.js +++ b/src/webapp/src/utils/ajax_post.js @@ -1,21 +1,13 @@ -const ajax_post = function(url, data = {}, callback) { - var xmlhttp = new XMLHttpRequest(); - xmlhttp.onreadystatechange = function() { - if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { - console.log('responseText:' + xmlhttp.responseText); - try { - var data = JSON.parse(xmlhttp.responseText); - } catch (err) { - console.log(err.message + ' in ' + xmlhttp.responseText); - return; - } - callback(data); - } - }; +import fetch from 'cross-fetch'; - xmlhttp.open('POST', url, true); - xmlhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); - xmlhttp.send(JSON.stringify(data)); +const ajax_post = function(url, data = {}) { + return fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json; charset=utf-8' + }, + body: JSON.stringify(data) + }); }; export default ajax_post; diff --git a/src/webapp/yarn.lock b/src/webapp/yarn.lock index dac6c8f..bad6406 100644 --- a/src/webapp/yarn.lock +++ b/src/webapp/yarn.lock @@ -1595,6 +1595,13 @@ create-hmac@^1.1.0, create-hmac@^1.1.2, create-hmac@^1.1.4: safe-buffer "^5.0.1" sha.js "^2.4.8" +cross-fetch@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/cross-fetch/-/cross-fetch-1.1.1.tgz#dede6865ae30f37eae62ac90ebb7bdac002b05a0" + dependencies: + node-fetch "1.7.3" + whatwg-fetch "2.0.3" + cross-spawn@5.1.0, cross-spawn@^5.0.1, cross-spawn@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-5.1.0.tgz#e8bd0efee58fcff6f8f94510a0a554bbfa235449" @@ -1779,6 +1786,10 @@ decamelize@^1.0.0, decamelize@^1.1.1, decamelize@^1.1.2: version "1.2.0" resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" +deep-diff@^0.3.5: + version "0.3.8" + resolved "https://registry.yarnpkg.com/deep-diff/-/deep-diff-0.3.8.tgz#c01de63efb0eec9798801d40c7e0dae25b582c84" + deep-equal@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/deep-equal/-/deep-equal-1.0.1.tgz#f5d260292b660e084eff4cdbc9f08ad3247448b5" @@ -2982,7 +2993,7 @@ hoek@4.x.x: version "4.2.1" resolved "https://registry.yarnpkg.com/hoek/-/hoek-4.2.1.tgz#9634502aa12c445dd5a7c5734b572bb8738aacbb" -hoist-non-react-statics@^2.3.0: +hoist-non-react-statics@^2.3.0, hoist-non-react-statics@^2.5.0: version "2.5.0" resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-2.5.0.tgz#d2ca2dfc19c5a91c5a6615ce8e564ef0347e2a40" @@ -3211,7 +3222,7 @@ interpret@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.1.0.tgz#7ed1b1410c6a0e0f78cf95d3b8440c63f78b8614" -invariant@^2.1.0, invariant@^2.2.1, invariant@^2.2.2: +invariant@^2.0.0, invariant@^2.1.0, invariant@^2.2.1, invariant@^2.2.2: version "2.2.3" resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.3.tgz#1a827dfde7dcbd7c323f0ca826be8fa7c5e9d688" dependencies: @@ -3965,6 +3976,10 @@ locate-path@^2.0.0: p-locate "^2.0.0" path-exists "^3.0.0" +lodash-es@^4.17.5, lodash-es@^4.2.1: + version "4.17.5" + resolved "https://registry.yarnpkg.com/lodash-es/-/lodash-es-4.17.5.tgz#9fc6e737b1c4d151d8f9cae2247305d552ce748f" + lodash._reinterpolate@~3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz#0ccf2d89166af03b3663c796538b75ac6e114d9d" @@ -4002,7 +4017,7 @@ lodash.uniq@^4.5.0: version "4.5.0" resolved "https://registry.yarnpkg.com/lodash.uniq/-/lodash.uniq-4.5.0.tgz#d0225373aeb652adc1bc82e4945339a842754773" -"lodash@>=3.5 <5", lodash@^4.14.0, lodash@^4.15.0, lodash@^4.17.2, lodash@^4.17.3, lodash@^4.17.4, lodash@^4.3.0: +"lodash@>=3.5 <5", lodash@^4.14.0, lodash@^4.15.0, lodash@^4.17.2, lodash@^4.17.3, lodash@^4.17.4, lodash@^4.17.5, lodash@^4.2.1, lodash@^4.3.0: version "4.17.5" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.5.tgz#99a92d65c0272debe8c96b6057bc8fbfa3bed511" @@ -4245,7 +4260,7 @@ no-case@^2.2.0: dependencies: lower-case "^1.1.1" -node-fetch@^1.0.1: +node-fetch@1.7.3, node-fetch@^1.0.1: version "1.7.3" resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-1.7.3.tgz#980f6f72d85211a5347c6b2bc18c5b84c3eb47ef" dependencies: @@ -5235,6 +5250,17 @@ react-prop-types@^0.4.0: dependencies: warning "^3.0.0" +react-redux@^5.0.7: + version "5.0.7" + resolved "https://registry.yarnpkg.com/react-redux/-/react-redux-5.0.7.tgz#0dc1076d9afb4670f993ffaef44b8f8c1155a4c8" + dependencies: + hoist-non-react-statics "^2.5.0" + invariant "^2.0.0" + lodash "^4.17.5" + lodash-es "^4.17.5" + loose-envify "^1.1.0" + prop-types "^15.6.0" + react-router-bootstrap@^0.24.4: version "0.24.4" resolved "https://registry.yarnpkg.com/react-router-bootstrap/-/react-router-bootstrap-0.24.4.tgz#6e89481d8a8979649a0dd4535e4a68df4a3d0b12" @@ -5415,6 +5441,25 @@ reduce-function-call@^1.0.1: dependencies: balanced-match "^0.4.2" +redux-logger@^3.0.6: + version "3.0.6" + resolved "https://registry.yarnpkg.com/redux-logger/-/redux-logger-3.0.6.tgz#f7555966f3098f3c88604c449cf0baf5778274bf" + dependencies: + deep-diff "^0.3.5" + +redux-thunk@^2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/redux-thunk/-/redux-thunk-2.2.0.tgz#e615a16e16b47a19a515766133d1e3e99b7852e5" + +redux@^3.7.2: + version "3.7.2" + resolved "https://registry.yarnpkg.com/redux/-/redux-3.7.2.tgz#06b73123215901d25d065be342eb026bc1c8537b" + dependencies: + lodash "^4.2.1" + lodash-es "^4.2.1" + loose-envify "^1.1.0" + symbol-observable "^1.0.3" + regenerate@^1.2.1: version "1.3.3" resolved "https://registry.yarnpkg.com/regenerate/-/regenerate-1.3.3.tgz#0c336d3980553d755c39b586ae3b20aa49c82b7f" @@ -6101,6 +6146,10 @@ sw-toolbox@^3.4.0: path-to-regexp "^1.0.1" serviceworker-cache-polyfill "^4.0.0" +symbol-observable@^1.0.3: + version "1.2.0" + resolved "https://registry.yarnpkg.com/symbol-observable/-/symbol-observable-1.2.0.tgz#c22688aed4eab3cdc2dfeacbb561660560a00804" + symbol-tree@^3.2.1: version "3.2.2" resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.2.tgz#ae27db38f660a7ae2e1c3b7d1bc290819b8519e6" From 12924b75f309069ce5c6e4f05b0aae45a81dc061 Mon Sep 17 00:00:00 2001 From: Liu Chao Date: Mon, 26 Feb 2018 10:37:31 +0800 Subject: [PATCH 27/54] Enable to login user --- src/webapp/src/App.js | 51 +++++++++++++++---- src/webapp/src/actions.js | 80 +++++++++++++++++++++++++++--- src/webapp/src/components/Home.js | 2 - src/webapp/src/components/Login.js | 48 ++++++++---------- src/webapp/src/reducers.js | 40 ++++++++++++++- src/webapp/src/utils/ajax_get.js | 10 +++- src/webapp/src/utils/ajax_post.js | 15 +++++- 7 files changed, 196 insertions(+), 50 deletions(-) diff --git a/src/webapp/src/App.js b/src/webapp/src/App.js index ae1e768..203859e 100644 --- a/src/webapp/src/App.js +++ b/src/webapp/src/App.js @@ -5,9 +5,38 @@ import Login from './components/Login'; import Signup from './components/Signup'; import { Navbar, Nav, NavItem, Grid, Row, Col } from 'react-bootstrap'; import { LinkContainer } from 'react-router-bootstrap'; +import { connect } from 'react-redux'; class App extends Component { + renderPublicLinks() { + return ( + + ); + } + + renderPrivateLinks() { + const { account } = this.props; + return ( + + ); + } + render() { + const { isAuthenticated } = this.props; return (
    @@ -18,14 +47,9 @@ class App extends Component { Home - + {isAuthenticated + ? this.renderPrivateLinks() + : this.renderPublicLinks()} @@ -44,4 +68,13 @@ class App extends Component { } } -export default App; +function mapStateToProps(state) { + const { account } = state; + const { isAuthenticated, data } = account; + return { + isAuthenticated, + account: data + }; +} + +export default connect(mapStateToProps)(App); diff --git a/src/webapp/src/actions.js b/src/webapp/src/actions.js index 57ba8e8..0a95e0a 100644 --- a/src/webapp/src/actions.js +++ b/src/webapp/src/actions.js @@ -1,10 +1,14 @@ import ajax_get from './utils/ajax_get'; +import ajax_post from './utils/ajax_post'; import API_Endpoints from './utils/API_Endpoints'; export const REQUEST_MEMBERS = 'REQUEST_MEMBERS'; export const RECEIVE_MEMBERS = 'RECEIVE_MEMBERS'; export const REQUEST_PUBLIC_DIARIES = 'REQUEST_PUBLIC_DIARIES'; export const RECEIVE_PUBLIC_DIARIES = 'RECEIVE_PUBLIC_DIARIES'; +export const REQUEST_USER = 'REQUEST_USER'; +export const RECEIVE_USER = 'RECEIVE_USER'; +export const HANDLE_AUTH_ERR = 'HANDLE_AUTH_ERR'; function requestMembers() { return { @@ -12,10 +16,10 @@ function requestMembers() { }; } -function receiveMembers(json) { +function receiveMembers(items) { return { type: RECEIVE_MEMBERS, - members: json.result + members: items }; } @@ -25,10 +29,10 @@ function requestPublicDiaires() { }; } -function receivePublicDiaries(json) { +function receivePublicDiaries(items) { return { type: RECEIVE_PUBLIC_DIARIES, - publicDiaries: json.result + publicDiaries: items }; } @@ -62,8 +66,70 @@ function getUrl(type) { export function fetchItems(type) { return dispatch => { dispatch(requestItems(type)); - return ajax_get(getUrl(type)) - .then(response => response.json()) - .then(json => dispatch(receiveItems(type, json))); + return ajax_get(getUrl(type)).then(data => + dispatch(receiveItems(type, data.result)) + ); + }; +} + +function requestUser(isFetching = true) { + return { + type: 'REQUEST_USER', + isFetching + }; +} + +function receiveUser({ username, fullname, age }) { + return { + type: 'RECEIVE_USER', + account: { + username, + fullname, + age + } + }; +} + +function handleAuthErr(error) { + return { + type: 'HANDLE_AUTH_ERR', + error + }; +} + +function fetchUser({ username, password }, dispatch) { + if (!username) { + dispatch(handleAuthErr('Username is required')); + } else if (!password) { + dispatch(handleAuthErr('Password is required')); + } else { + dispatch(requestUser(true)); + return ajax_post(API_Endpoints.authenticate_user, { username, password }) + .then(data => { + sessionStorage.setItem('token', data.token); + }) + .catch(() => { + const error = 'Username or password is invalid'; + dispatch(handleAuthErr(error)); + throw error; + }) + .then(() => { + return ajax_post(API_Endpoints.get_user, {}, true); + }) + .then(data => { + dispatch(receiveUser(data)); + }) + .catch(error => { + dispatch(handleAuthErr(error)); + }) + .finally(() => { + dispatch(requestUser(false)); + }); + } +} + +export function login(data) { + return dispatch => { + return fetchUser(data, dispatch); }; } diff --git a/src/webapp/src/components/Home.js b/src/webapp/src/components/Home.js index 720f602..a109711 100644 --- a/src/webapp/src/components/Home.js +++ b/src/webapp/src/components/Home.js @@ -1,6 +1,4 @@ import React, { Component } from 'react'; -import ajax_get from '../utils/ajax_get'; -import API_Endpoints from '../utils/API_Endpoints'; import { PageHeader, Panel } from 'react-bootstrap'; import Diaries from './Diaries.js'; import FontAwesome from 'react-fontawesome'; diff --git a/src/webapp/src/components/Login.js b/src/webapp/src/components/Login.js index 1c6b190..9ad093d 100644 --- a/src/webapp/src/components/Login.js +++ b/src/webapp/src/components/Login.js @@ -12,6 +12,8 @@ import { Panel } from 'react-bootstrap'; import FontAwesome from 'react-fontawesome'; +import { connect } from 'react-redux'; +import { login } from '../actions'; class Login extends Component { constructor(props) { @@ -36,35 +38,12 @@ class Login extends Component { const username = (this.usernameField.value || '').trim(); const password = (this.passwordField.value || '').trim(); - if (!username) { - this.setError('Username is required'); - } else if (!password) { - this.setError('Password is required'); - } else { - this.setState({ - isLoading: true - }); - ajax_post( - API_Endpoints.authenticate_user, - { username, password }, - data => { - this.setState({ - isLoading: false - }); - if (data.status) { - this.setMessage('Login successfully'); - } else { - this.passwordField.value = ''; - this.passwordField.focus(); - this.setState({ error: 'Invalid username or password' }); - } - } - ); - } + this.props.login({ username, password }); + // TODO: clear password field if username or password is invalid } render() { - const { error, message, isLoading } = this.state; + const { error, message, isLoading } = this.props; return ( @@ -118,4 +97,19 @@ class Login extends Component { } } -export default Login; +function mapStateToProps(state) { + const { account } = state; + const { isFetching: isLoading, error } = account; + return { + isLoading, + error + }; +} + +function mapDispatchToProps(dispatch) { + return { + login: data => dispatch(login(data)) + }; +} + +export default connect(mapStateToProps, mapDispatchToProps)(Login); diff --git a/src/webapp/src/reducers.js b/src/webapp/src/reducers.js index 0987714..21222ae 100644 --- a/src/webapp/src/reducers.js +++ b/src/webapp/src/reducers.js @@ -3,7 +3,10 @@ import { REQUEST_MEMBERS, RECEIVE_MEMBERS, REQUEST_PUBLIC_DIARIES, - RECEIVE_PUBLIC_DIARIES + RECEIVE_PUBLIC_DIARIES, + REQUEST_USER, + RECEIVE_USER, + HANDLE_AUTH_ERR } from './actions'; function members( @@ -50,8 +53,41 @@ function publicDiaries( } } +function account( + state = { + isAuthenticated: false, + isFetching: false, + error: '', + data: { + fullname: '', + username: '', + age: '' + } + }, + action +) { + switch (action.type) { + case 'REQUEST_USER': + return Object.assign({}, state, { + isFetching: action.isFetching + }); + case 'HANDLE_AUTH_ERR': + return Object.assign({}, state, { + error: action.error + }); + case 'RECEIVE_USER': + return Object.assign({}, state, { + isAuthenticated: true, + data: action.account + }); + default: + return state; + } +} + const rootReducer = combineReducers({ members, - publicDiaries + publicDiaries, + account }); export default rootReducer; diff --git a/src/webapp/src/utils/ajax_get.js b/src/webapp/src/utils/ajax_get.js index d39dcfc..1403189 100644 --- a/src/webapp/src/utils/ajax_get.js +++ b/src/webapp/src/utils/ajax_get.js @@ -1,7 +1,15 @@ import fetch from 'cross-fetch'; const ajax_get = function(url) { - return fetch(url); + return fetch(url) + .then(response => response.json()) + .then(data => { + if (data.status) { + return data; + } else { + throw data.error; + } + }); }; export default ajax_get; diff --git a/src/webapp/src/utils/ajax_post.js b/src/webapp/src/utils/ajax_post.js index 376303d..624da2d 100644 --- a/src/webapp/src/utils/ajax_post.js +++ b/src/webapp/src/utils/ajax_post.js @@ -1,13 +1,24 @@ import fetch from 'cross-fetch'; -const ajax_post = function(url, data = {}) { +const ajax_post = function(url, data = {}, isAuthenticated = false) { + if (isAuthenticated) { + data.token = sessionStorage.getItem('token'); + } return fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json; charset=utf-8' }, body: JSON.stringify(data) - }); + }) + .then(response => response.json()) + .then(data => { + if (data.status) { + return data; + } else { + throw data.error; + } + }); }; export default ajax_post; From 1041c827a9aaa060866df6bbac616e1789f5f9d8 Mon Sep 17 00:00:00 2001 From: Liu Chao Date: Mon, 26 Feb 2018 14:35:45 +0800 Subject: [PATCH 28/54] Show account information --- src/webapp/src/App.js | 9 ++-- src/webapp/src/actions.js | 1 + src/webapp/src/components/Account.js | 62 +++++++++++++++++++++++++++ src/webapp/src/components/NewDiary.js | 0 src/webapp/src/components/index.js | 7 +++ 5 files changed, 76 insertions(+), 3 deletions(-) create mode 100644 src/webapp/src/components/Account.js create mode 100644 src/webapp/src/components/NewDiary.js create mode 100644 src/webapp/src/components/index.js diff --git a/src/webapp/src/App.js b/src/webapp/src/App.js index 203859e..f830972 100644 --- a/src/webapp/src/App.js +++ b/src/webapp/src/App.js @@ -1,8 +1,6 @@ import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; -import Home from './components/Home'; -import Login from './components/Login'; -import Signup from './components/Signup'; +import { Home, Login, Signup, Account, NewDiary } from './components'; import { Navbar, Nav, NavItem, Grid, Row, Col } from 'react-bootstrap'; import { LinkContainer } from 'react-router-bootstrap'; import { connect } from 'react-redux'; @@ -31,6 +29,9 @@ class App extends Component { New Diary + + Log Out + ); } @@ -58,6 +59,8 @@ class App extends Component { + + diff --git a/src/webapp/src/actions.js b/src/webapp/src/actions.js index 0a95e0a..b190601 100644 --- a/src/webapp/src/actions.js +++ b/src/webapp/src/actions.js @@ -117,6 +117,7 @@ function fetchUser({ username, password }, dispatch) { return ajax_post(API_Endpoints.get_user, {}, true); }) .then(data => { + sessionStorage.setItem('account', JSON.stringify(data)); dispatch(receiveUser(data)); }) .catch(error => { diff --git a/src/webapp/src/components/Account.js b/src/webapp/src/components/Account.js new file mode 100644 index 0000000..59777bf --- /dev/null +++ b/src/webapp/src/components/Account.js @@ -0,0 +1,62 @@ +import React, { Component } from 'react'; +import { + Col, + ControlLabel, + Form, + FormControl, + FormGroup, + Panel +} from 'react-bootstrap'; +import { connect } from 'react-redux'; + +class Account extends Component { + render() { + const { account } = this.props; + return ( + + + Account + + +
    + + + Full Name + + + {account.fullname} + + + + + + Age + + + {account.age} + + + + + + Username + + + {account.username} + + +
    +
    +
    + ); + } +} + +function mapStateToProps(state) { + const { data: account } = state.account; + return { + account + }; +} + +export default connect(mapStateToProps)(Account); diff --git a/src/webapp/src/components/NewDiary.js b/src/webapp/src/components/NewDiary.js new file mode 100644 index 0000000..e69de29 diff --git a/src/webapp/src/components/index.js b/src/webapp/src/components/index.js new file mode 100644 index 0000000..81aeb91 --- /dev/null +++ b/src/webapp/src/components/index.js @@ -0,0 +1,7 @@ +export { default as Account } from './Account'; +export { default as Diaries } from './Diaries'; +export { default as Diary } from './Diary'; +export { default as Home } from './Home'; +export { default as Login } from './Login'; +export { default as NewDiary } from './NewDiary'; +export { default as Signup } from './Signup'; From b3c2d206ed4c191be818f50b491b5c4f6cc7da44 Mon Sep 17 00:00:00 2001 From: Liu Chao Date: Tue, 27 Feb 2018 07:47:00 +0800 Subject: [PATCH 29/54] Enalbe to log user out --- src/webapp/src/App.js | 26 ++++++- src/webapp/src/actions.js | 45 +++++++++++- src/webapp/src/components/Diaries.js | 2 +- src/webapp/src/components/Home.js | 2 +- src/webapp/src/components/Login.js | 105 +++++++++++++-------------- src/webapp/src/components/Logout.js | 41 +++++++++++ src/webapp/src/components/index.js | 1 + src/webapp/src/index.js | 1 - src/webapp/src/reducers.js | 22 +++--- 9 files changed, 170 insertions(+), 75 deletions(-) create mode 100644 src/webapp/src/components/Logout.js diff --git a/src/webapp/src/App.js b/src/webapp/src/App.js index f830972..0364eb0 100644 --- a/src/webapp/src/App.js +++ b/src/webapp/src/App.js @@ -1,11 +1,17 @@ import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; -import { Home, Login, Signup, Account, NewDiary } from './components'; +import { Home, Login, Signup, Account, NewDiary, Logout } from './components'; import { Navbar, Nav, NavItem, Grid, Row, Col } from 'react-bootstrap'; -import { LinkContainer } from 'react-router-bootstrap'; +import { Button, LinkContainer } from 'react-router-bootstrap'; import { connect } from 'react-redux'; +import { checkIsAuthenticated, logout } from './actions'; class App extends Component { + componentWillMount() { + const { checkAuthentication } = this.props; + checkAuthentication(); + } + renderPublicLinks() { return ( ); @@ -60,6 +70,7 @@ class App extends Component { + @@ -80,4 +91,11 @@ function mapStateToProps(state) { }; } -export default connect(mapStateToProps)(App); +function mapDispatchToProps(dispatch) { + return { + logout: () => dispatch(logout()), + checkAuthentication: () => dispatch(checkIsAuthenticated()) + }; +} + +export default connect(mapStateToProps, mapDispatchToProps)(App); diff --git a/src/webapp/src/actions.js b/src/webapp/src/actions.js index b190601..745af4e 100644 --- a/src/webapp/src/actions.js +++ b/src/webapp/src/actions.js @@ -9,6 +9,7 @@ export const RECEIVE_PUBLIC_DIARIES = 'RECEIVE_PUBLIC_DIARIES'; export const REQUEST_USER = 'REQUEST_USER'; export const RECEIVE_USER = 'RECEIVE_USER'; export const HANDLE_AUTH_ERR = 'HANDLE_AUTH_ERR'; +export const UNAUTHENTICATE_USER = 'UNAUTHENTICATE_USER'; function requestMembers() { return { @@ -74,14 +75,14 @@ export function fetchItems(type) { function requestUser(isFetching = true) { return { - type: 'REQUEST_USER', + type: REQUEST_USER, isFetching }; } function receiveUser({ username, fullname, age }) { return { - type: 'RECEIVE_USER', + type: RECEIVE_USER, account: { username, fullname, @@ -92,11 +93,17 @@ function receiveUser({ username, fullname, age }) { function handleAuthErr(error) { return { - type: 'HANDLE_AUTH_ERR', + type: HANDLE_AUTH_ERR, error }; } +function removeUser() { + return { + type: UNAUTHENTICATE_USER + }; +} + function fetchUser({ username, password }, dispatch) { if (!username) { dispatch(handleAuthErr('Username is required')); @@ -134,3 +141,35 @@ export function login(data) { return fetchUser(data, dispatch); }; } + +export function logout() { + return dispatch => { + const token = sessionStorage.getItem('token'); + if (!token) { + return; + } + dispatch(requestUser()); + ajax_post(API_Endpoints.expire_user, {}, true) + .then(() => { + sessionStorage.removeItem('token'); + sessionStorage.removeItem('account'); + dispatch(removeUser()); + }) + .catch(error => { + dispatch(handleAuthErr(error)); + }) + .finally(() => { + dispatch(requestUser(false)); + }); + }; +} + +export function checkIsAuthenticated() { + return dispatch => { + const isAuthenticated = sessionStorage.getItem('token'); + const account = sessionStorage.getItem('account'); + if (isAuthenticated && account) { + return dispatch(receiveUser(JSON.parse(account))); + } + }; +} diff --git a/src/webapp/src/components/Diaries.js b/src/webapp/src/components/Diaries.js index 271d13c..d17b21f 100644 --- a/src/webapp/src/components/Diaries.js +++ b/src/webapp/src/components/Diaries.js @@ -8,7 +8,7 @@ class Diaries extends Component { if (isLoading) { return ( - Loading... + Loading... ); } else if (diaries.length) { diff --git a/src/webapp/src/components/Home.js b/src/webapp/src/components/Home.js index a109711..7e36191 100644 --- a/src/webapp/src/components/Home.js +++ b/src/webapp/src/components/Home.js @@ -17,7 +17,7 @@ class Home extends Component { if (isLoadingMembers) { return ( - Loading... + Loading... ); } else { diff --git a/src/webapp/src/components/Login.js b/src/webapp/src/components/Login.js index 9ad093d..c6f2084 100644 --- a/src/webapp/src/components/Login.js +++ b/src/webapp/src/components/Login.js @@ -16,23 +16,6 @@ import { connect } from 'react-redux'; import { login } from '../actions'; class Login extends Component { - constructor(props) { - super(props); - this.state = { - error: '', - message: '', - isLoading: false - }; - } - - setError(error) { - this.setState({ error }); - } - - setMessage(message) { - this.setState({ message }); - } - handleLogin(e) { e.preventDefault(); const username = (this.usernameField.value || '').trim(); @@ -42,8 +25,48 @@ class Login extends Component { // TODO: clear password field if username or password is invalid } + renderForm() { + const { isLoading } = this.props; + return ( +
    + + + Username + + + (this.usernameField = ref)} + /> + + + + + Password + + + (this.passwordField = ref)} + /> + + + + + + + +
    + ); + } + render() { - const { error, message, isLoading } = this.props; + const { error, account } = this.props; return ( @@ -52,45 +75,14 @@ class Login extends Component { {error ? ( {error} - ) : message ? ( - {message} + ) : account.username ? ( + + You are logged in successfully as {account.username} + ) : ( '' )} -
    - - - Username - - - (this.usernameField = ref)} - /> - - - - - Password - - - (this.passwordField = ref)} - /> - - - - - - - -
    + {!account.username ? this.renderForm() : ''}
    ); @@ -99,10 +91,11 @@ class Login extends Component { function mapStateToProps(state) { const { account } = state; - const { isFetching: isLoading, error } = account; + const { isFetching: isLoading, error, data } = account; return { isLoading, - error + error, + account: data }; } diff --git a/src/webapp/src/components/Logout.js b/src/webapp/src/components/Logout.js new file mode 100644 index 0000000..260ea2c --- /dev/null +++ b/src/webapp/src/components/Logout.js @@ -0,0 +1,41 @@ +import React, { Component } from 'react'; +import { Panel, Alert } from 'react-bootstrap'; +import { connect } from 'react-redux'; +import { FontAwesome } from 'react-fontawesome'; +import { logout } from '../actions'; + +class Logout extends Component { + componentDidMount() { + const { dispatch } = this.props; + dispatch(logout()); + } + + render() { + const { isLoading, isAuthenticated } = this.props; + return ( + + + Log Out + + + {isLoading ? ( + 'Loading...' + ) : ( + You are logged out successfully. + )} + + + ); + } +} + +function mapStateToProps(state) { + const { account } = state; + const { isFetching: isLoading, isAuthenticated } = account; + return { + isLoading, + isAuthenticated + }; +} + +export default connect(mapStateToProps)(Logout); diff --git a/src/webapp/src/components/index.js b/src/webapp/src/components/index.js index 81aeb91..7768875 100644 --- a/src/webapp/src/components/index.js +++ b/src/webapp/src/components/index.js @@ -3,5 +3,6 @@ export { default as Diaries } from './Diaries'; export { default as Diary } from './Diary'; export { default as Home } from './Home'; export { default as Login } from './Login'; +export { default as Logout } from './Logout'; export { default as NewDiary } from './NewDiary'; export { default as Signup } from './Signup'; diff --git a/src/webapp/src/index.js b/src/webapp/src/index.js index f11dfe6..7f2db13 100644 --- a/src/webapp/src/index.js +++ b/src/webapp/src/index.js @@ -1,7 +1,6 @@ import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; -import { createStore } from 'redux'; import { Provider } from 'react-redux'; import configureStore from './configureStore'; import registerServiceWorker from './registerServiceWorker'; diff --git a/src/webapp/src/reducers.js b/src/webapp/src/reducers.js index 21222ae..cc4dd7c 100644 --- a/src/webapp/src/reducers.js +++ b/src/webapp/src/reducers.js @@ -6,7 +6,8 @@ import { RECEIVE_PUBLIC_DIARIES, REQUEST_USER, RECEIVE_USER, - HANDLE_AUTH_ERR + HANDLE_AUTH_ERR, + UNAUTHENTICATE_USER } from './actions'; function members( @@ -58,28 +59,31 @@ function account( isAuthenticated: false, isFetching: false, error: '', - data: { - fullname: '', - username: '', - age: '' - } + data: {} }, action ) { switch (action.type) { - case 'REQUEST_USER': + case REQUEST_USER: return Object.assign({}, state, { isFetching: action.isFetching }); - case 'HANDLE_AUTH_ERR': + case HANDLE_AUTH_ERR: return Object.assign({}, state, { error: action.error }); - case 'RECEIVE_USER': + case RECEIVE_USER: return Object.assign({}, state, { + error: '', isAuthenticated: true, data: action.account }); + case UNAUTHENTICATE_USER: + return Object.assign({}, state, { + error: '', + isAuthenticated: false, + data: {} + }); default: return state; } From 0ef42f6a8b20e93afa12a52f5bb19e4d161a2288 Mon Sep 17 00:00:00 2001 From: Liu Chao Date: Tue, 27 Feb 2018 09:20:02 +0800 Subject: [PATCH 30/54] Enable to create new diary --- src/webapp/src/actions.js | 9 +- src/webapp/src/components/NewDiary.js | 132 ++++++++++++++++++++++++++ src/webapp/src/components/Signup.js | 20 ++-- 3 files changed, 147 insertions(+), 14 deletions(-) diff --git a/src/webapp/src/actions.js b/src/webapp/src/actions.js index 745af4e..ab9a28f 100644 --- a/src/webapp/src/actions.js +++ b/src/webapp/src/actions.js @@ -150,15 +150,14 @@ export function logout() { } dispatch(requestUser()); ajax_post(API_Endpoints.expire_user, {}, true) - .then(() => { - sessionStorage.removeItem('token'); - sessionStorage.removeItem('account'); - dispatch(removeUser()); - }) .catch(error => { dispatch(handleAuthErr(error)); }) .finally(() => { + // remove all session data + sessionStorage.removeItem('token'); + sessionStorage.removeItem('account'); + dispatch(removeUser()); dispatch(requestUser(false)); }); }; diff --git a/src/webapp/src/components/NewDiary.js b/src/webapp/src/components/NewDiary.js index e69de29..17bfa90 100644 --- a/src/webapp/src/components/NewDiary.js +++ b/src/webapp/src/components/NewDiary.js @@ -0,0 +1,132 @@ +import React, { Component } from 'react'; +import ajax_post from '../utils/ajax_post'; +import API_Endpoints from '../utils/API_Endpoints'; +import { + Alert, + Form, + FormGroup, + FormControl, + Button, + Col, + ControlLabel, + Panel +} from 'react-bootstrap'; +import FontAwesome from 'react-fontawesome'; + +class NewDiary extends Component { + constructor(props) { + super(props); + this.state = { + error: '', + message: '', + isLoading: false + }; + } + + setError(error) { + this.setState({ error }); + } + + setMessage(message) { + this.setState({ message }); + } + + handleCreate(e) { + e.preventDefault(); + const title = (this.titleField.value || '').trim(); + const text = (this.textField.value || '').trim(); + + if (!title) { + this.setError('Title is required'); + } else if (!text) { + this.setError('Text is required'); + } else { + this.setState({ + isLoading: true + }); + ajax_post( + API_Endpoints.create_diary, + { + title, + text, + public: false + }, + true + ) + .then(() => { + this.setMessage('New Diary created successfully'); + }) + .catch(error => { + this.setError(error); + }) + .finally(() => { + this.setState({ + isLoading: false + }); + }); + } + } + + renderForm() { + const { isLoading } = this.state; + return ( +
    + + + Title + + + (this.titleField = ref)} + /> + + + + + Text + + + (this.textField = ref)} + /> + + + + + + + +
    + ); + } + + render() { + const { error, message } = this.state; + return ( + + + New Diary + + + {error ? ( + {error} + ) : message ? ( + {message} + ) : ( + '' + )} + {!message ? this.renderForm() : ''} + + + ); + } +} + +export default NewDiary; diff --git a/src/webapp/src/components/Signup.js b/src/webapp/src/components/Signup.js index 9dc76cd..ceb99ea 100644 --- a/src/webapp/src/components/Signup.js +++ b/src/webapp/src/components/Signup.js @@ -55,16 +55,18 @@ class Signup extends Component { age, username, password - }).then(data => { - this.setState({ - isLoading: false - }); - if (data.status) { + }) + .then(() => { this.setMessage('Account created successfully'); - } else { - this.setError(data.error); - } - }); + }) + .catch(error => { + this.setError(error); + }) + .finally(() => { + this.setState({ + isLoading: false + }); + }); } } From 17bed8dff7bd23b2507c4be93040449258eb6e2b Mon Sep 17 00:00:00 2001 From: Liu Chao Date: Tue, 27 Feb 2018 15:32:26 +0800 Subject: [PATCH 31/54] Enable to delete diary --- src/webapp/package.json | 1 + src/webapp/src/App.js | 27 ++++- src/webapp/src/actions.js | 92 ++++++++++++++-- src/webapp/src/components/Diaries.js | 53 +++++++-- src/webapp/src/components/Diary.js | 10 -- src/webapp/src/components/Home.js | 47 ++++++-- src/webapp/src/components/Login.js | 2 - src/webapp/src/components/Logout.js | 1 - src/webapp/src/components/index.js | 1 - src/webapp/src/reducers.js | 67 ++++++++++- src/webapp/src/utils/API_Endpoints.js | 2 +- src/webapp/yarn.lock | 153 +++++++++++++++++++++++++- 12 files changed, 404 insertions(+), 52 deletions(-) delete mode 100644 src/webapp/src/components/Diary.js diff --git a/src/webapp/package.json b/src/webapp/package.json index 0886ca5..0c33a4f 100644 --- a/src/webapp/package.json +++ b/src/webapp/package.json @@ -8,6 +8,7 @@ "font-awesome": "^4.7.0", "react": "^16.2.0", "react-bootstrap": "^0.32.1", + "react-bs-notifier": "^4.4.6", "react-dom": "^16.2.0", "react-fontawesome": "^1.6.1", "react-redux": "^5.0.7", diff --git a/src/webapp/src/App.js b/src/webapp/src/App.js index 0364eb0..6240563 100644 --- a/src/webapp/src/App.js +++ b/src/webapp/src/App.js @@ -4,7 +4,8 @@ import { Home, Login, Signup, Account, NewDiary, Logout } from './components'; import { Navbar, Nav, NavItem, Grid, Row, Col } from 'react-bootstrap'; import { Button, LinkContainer } from 'react-router-bootstrap'; import { connect } from 'react-redux'; -import { checkIsAuthenticated, logout } from './actions'; +import { checkIsAuthenticated, logout, dismissAlert } from './actions'; +import { Alert, AlertContainer } from 'react-bs-notifier'; class App extends Component { componentWillMount() { @@ -47,9 +48,23 @@ class App extends Component { } render() { - const { isAuthenticated } = this.props; + const { isAuthenticated, alerts, dismissAlert } = this.props; return (
    + + {alerts.map(alert => { + return ( + dismissAlert(alert)} + > + {alert.message} + + ); + })} +
    @@ -83,18 +98,20 @@ class App extends Component { } function mapStateToProps(state) { - const { account } = state; + const { account, alerts } = state; const { isAuthenticated, data } = account; return { isAuthenticated, - account: data + account: data, + alerts }; } function mapDispatchToProps(dispatch) { return { logout: () => dispatch(logout()), - checkAuthentication: () => dispatch(checkIsAuthenticated()) + checkAuthentication: () => dispatch(checkIsAuthenticated()), + dismissAlert: alert => dispatch(dismissAlert(alert)) }; } diff --git a/src/webapp/src/actions.js b/src/webapp/src/actions.js index ab9a28f..573c749 100644 --- a/src/webapp/src/actions.js +++ b/src/webapp/src/actions.js @@ -6,10 +6,15 @@ export const REQUEST_MEMBERS = 'REQUEST_MEMBERS'; export const RECEIVE_MEMBERS = 'RECEIVE_MEMBERS'; export const REQUEST_PUBLIC_DIARIES = 'REQUEST_PUBLIC_DIARIES'; export const RECEIVE_PUBLIC_DIARIES = 'RECEIVE_PUBLIC_DIARIES'; +export const REQUEST_MY_DIARIES = 'REQUEST_MY_DIARIES'; +export const RECEIVE_MY_DIARIES = 'RECEIVE_MY_DIARIES'; export const REQUEST_USER = 'REQUEST_USER'; export const RECEIVE_USER = 'RECEIVE_USER'; export const HANDLE_AUTH_ERR = 'HANDLE_AUTH_ERR'; export const UNAUTHENTICATE_USER = 'UNAUTHENTICATE_USER'; +export const REMOVE_DIARY = 'REMOVE_DIARY'; +export const SHOW_ALERT = 'SHOW_ALERT'; +export const DISMISS_ALERT = 'DISMISS_ALERT'; function requestMembers() { return { @@ -33,7 +38,20 @@ function requestPublicDiaires() { function receivePublicDiaries(items) { return { type: RECEIVE_PUBLIC_DIARIES, - publicDiaries: items + diaries: items + }; +} + +function requestMyDiaries() { + return { + type: REQUEST_MY_DIARIES + }; +} + +function receiveMyDiaries(items) { + return { + type: RECEIVE_MY_DIARIES, + diaries: items }; } @@ -43,15 +61,19 @@ function requestItems(type) { return requestMembers(); case 'public-diaries': return requestPublicDiaires(); + case 'my-diaries': + return requestMyDiaries(); } } -function receiveItems(type, json) { +function receiveItems(type, items) { switch (type) { case 'members': - return receiveMembers(json); + return receiveMembers(items); case 'public-diaries': - return receivePublicDiaries(json); + return receivePublicDiaries(items); + case 'my-diaries': + return receiveMyDiaries(items); } } @@ -61,15 +83,21 @@ function getUrl(type) { return API_Endpoints.get_members; case 'public-diaries': return API_Endpoints.get_public_diaries; + case 'my-diaries': + return API_Endpoints.get_my_diaries; } } export function fetchItems(type) { return dispatch => { dispatch(requestItems(type)); - return ajax_get(getUrl(type)).then(data => - dispatch(receiveItems(type, data.result)) - ); + let promise; + if (type === 'my-diaries') { + promise = ajax_post(getUrl(type), {}, true); + } else { + promise = ajax_get(getUrl(type)); + } + return promise.then(data => dispatch(receiveItems(type, data.result))); }; } @@ -172,3 +200,53 @@ export function checkIsAuthenticated() { } }; } + +function removeDiary(diary) { + return { + type: REMOVE_DIARY, + diary + }; +} + +export function showAlert(alert) { + return { + type: SHOW_ALERT, + alert + }; +} + +export function dismissAlert(alert) { + return { + type: DISMISS_ALERT, + alert + }; +} + +export function deleteDiary(diary) { + return dispatch => { + dispatch(removeDiary(diary)); + return ajax_post( + API_Endpoints.delete_diary, + { + id: diary.id + }, + true + ) + .then(() => { + dispatch( + showAlert({ + type: 'success', + message: 'Diary is deleted successfully' + }) + ); + }) + .catch(error => { + dispatch( + showAlert({ + type: 'danger', + message: error + }) + ); + }); + }; +} diff --git a/src/webapp/src/components/Diaries.js b/src/webapp/src/components/Diaries.js index d17b21f..e1a1b0c 100644 --- a/src/webapp/src/components/Diaries.js +++ b/src/webapp/src/components/Diaries.js @@ -1,10 +1,19 @@ import React, { Component } from 'react'; import FontAwesome from 'react-fontawesome'; -import Diary from './Diary'; +import { + Button, + ButtonToolbar, + Col, + ListGroup, + ListGroupItem, + Row +} from 'react-bootstrap'; +import { connect } from 'react-redux'; +import { deleteDiary } from '../actions'; class Diaries extends Component { render() { - const { isLoading, diaries } = this.props; + const { isLoading, diaries, deleteDiary } = this.props; if (isLoading) { return ( @@ -13,15 +22,37 @@ class Diaries extends Component { ); } else if (diaries.length) { return ( -
      + {diaries.map(diary => { return ( -
    • - -
    • + + + +

      + {diary.title} +

      +

      {diary.text}

      + + {diary.public ? ( + '' + ) : ( + + + + + + )} +
      +
      ); })} -
    + ); } else { return No data found; @@ -29,4 +60,10 @@ class Diaries extends Component { } } -export default Diaries; +function mapDispatchToProps(dispatch) { + return { + deleteDiary: diary => dispatch(deleteDiary(diary)) + }; +} + +export default connect(null, mapDispatchToProps)(Diaries); diff --git a/src/webapp/src/components/Diary.js b/src/webapp/src/components/Diary.js deleted file mode 100644 index 4bcc27c..0000000 --- a/src/webapp/src/components/Diary.js +++ /dev/null @@ -1,10 +0,0 @@ -import React, { Component } from 'react'; - -class Diary extends Component { - render() { - const { diary } = this.props; - return 'hello world'; - } -} - -export default Diary; diff --git a/src/webapp/src/components/Home.js b/src/webapp/src/components/Home.js index 7e36191..b69fd8d 100644 --- a/src/webapp/src/components/Home.js +++ b/src/webapp/src/components/Home.js @@ -10,6 +10,9 @@ class Home extends Component { const { dispatch } = this.props; dispatch(fetchItems('members')); dispatch(fetchItems('public-diaries')); + if (this.props.isAuthenticated) { + dispatch(fetchItems('my-diaries')); + } } renderMembers() { @@ -32,7 +35,13 @@ class Home extends Component { } render() { - const { isLoadingPublicDiaries, publicDiaries } = this.props; + const { + isAuthenticated, + isLoadingPublicDiaries, + publicDiaries, + isLoadingMyDiaries, + myDiaries + } = this.props; return (
    @@ -54,29 +63,45 @@ class Home extends Component { /> + {isAuthenticated ? ( + + + My Diaries + + + + + + ) : ( + '' + )}
    ); } } function mapStateToProps(state) { - const { members: allMembers, publicDiaries: allPublicDiaries } = state; - const { isFetching: isLoadingMembers, items: members } = allMembers || { - isFetching: true, - items: [] - }; + const { + members: allMembers, + publicDiaries: allPublicDiaries, + myDiaries: allMyDiaries, + account + } = state; + const { isFetching: isLoadingMembers, items: members } = allMembers; const { isFetching: isLoadingPublicDiaries, items: publicDiaries - } = allPublicDiaries || { - isFetching: true, - items: [] - }; + } = allPublicDiaries; + const { isFetching: isLoadingMyDiaries, items: myDiaries } = allMyDiaries; + const { isAuthenticated } = account; return { + isAuthenticated, isLoadingMembers, members, isLoadingPublicDiaries, - publicDiaries + publicDiaries, + isLoadingMyDiaries, + myDiaries }; } diff --git a/src/webapp/src/components/Login.js b/src/webapp/src/components/Login.js index c6f2084..73db15c 100644 --- a/src/webapp/src/components/Login.js +++ b/src/webapp/src/components/Login.js @@ -1,6 +1,4 @@ import React, { Component } from 'react'; -import ajax_post from '../utils/ajax_post'; -import API_Endpoints from '../utils/API_Endpoints'; import { Alert, Form, diff --git a/src/webapp/src/components/Logout.js b/src/webapp/src/components/Logout.js index 260ea2c..4d73abf 100644 --- a/src/webapp/src/components/Logout.js +++ b/src/webapp/src/components/Logout.js @@ -1,7 +1,6 @@ import React, { Component } from 'react'; import { Panel, Alert } from 'react-bootstrap'; import { connect } from 'react-redux'; -import { FontAwesome } from 'react-fontawesome'; import { logout } from '../actions'; class Logout extends Component { diff --git a/src/webapp/src/components/index.js b/src/webapp/src/components/index.js index 7768875..881def0 100644 --- a/src/webapp/src/components/index.js +++ b/src/webapp/src/components/index.js @@ -1,6 +1,5 @@ export { default as Account } from './Account'; export { default as Diaries } from './Diaries'; -export { default as Diary } from './Diary'; export { default as Home } from './Home'; export { default as Login } from './Login'; export { default as Logout } from './Logout'; diff --git a/src/webapp/src/reducers.js b/src/webapp/src/reducers.js index cc4dd7c..0d2acca 100644 --- a/src/webapp/src/reducers.js +++ b/src/webapp/src/reducers.js @@ -4,10 +4,15 @@ import { RECEIVE_MEMBERS, REQUEST_PUBLIC_DIARIES, RECEIVE_PUBLIC_DIARIES, + REQUEST_MY_DIARIES, + RECEIVE_MY_DIARIES, REQUEST_USER, RECEIVE_USER, HANDLE_AUTH_ERR, - UNAUTHENTICATE_USER + UNAUTHENTICATE_USER, + REMOVE_DIARY, + SHOW_ALERT, + DISMISS_ALERT } from './actions'; function members( @@ -32,6 +37,15 @@ function members( } } +function removeDiary(state = [], action) { + switch (action.type) { + case REMOVE_DIARY: + const { diary } = action; + const index = state.indexOf(diary); + return [...state.slice(0, index), ...state.slice(index + 1)]; + } +} + function publicDiaries( state = { isFetching: false, @@ -47,7 +61,37 @@ function publicDiaries( case RECEIVE_PUBLIC_DIARIES: return Object.assign({}, state, { isFetching: false, - items: action.publicDiaries + items: action.diaries + }); + case REMOVE_DIARY: + return Object.assign({}, state, { + items: removeDiary(state.items, action) + }); + default: + return state; + } +} + +function myDiaries( + state = { + isFetching: false, + items: [] + }, + action +) { + switch (action.type) { + case REQUEST_MY_DIARIES: + return Object.assign({}, state, { + isFetching: true + }); + case RECEIVE_MY_DIARIES: + return Object.assign({}, state, { + isFetching: false, + items: action.diaries + }); + case REMOVE_DIARY: + return Object.assign({}, state, { + items: removeDiary(state.items, action) }); default: return state; @@ -89,9 +133,26 @@ function account( } } +function alerts(state = [], action) { + const { alert } = action; + + switch (action.type) { + case SHOW_ALERT: + alert.id = state.length + 1; + return [...state, alert]; + case DISMISS_ALERT: + const index = state.indexOf(alert); + return [...state.slice(0, index), ...state.slice(index + 1)]; + default: + return state; + } +} + const rootReducer = combineReducers({ members, publicDiaries, - account + myDiaries, + account, + alerts }); export default rootReducer; diff --git a/src/webapp/src/utils/API_Endpoints.js b/src/webapp/src/utils/API_Endpoints.js index 06f2eea..fae65b2 100644 --- a/src/webapp/src/utils/API_Endpoints.js +++ b/src/webapp/src/utils/API_Endpoints.js @@ -7,7 +7,7 @@ const relativePaths = { expire_user: '/users/expire', get_user: '/users', get_public_diaries: '/diary', - get_private_diaries: '/diary', + get_my_diaries: '/diary', create_diary: '/diary/create', delete_diary: '/diary/delete', toggle_diary_permission: '/diary/permission' diff --git a/src/webapp/yarn.lock b/src/webapp/yarn.lock index bad6406..4190eee 100644 --- a/src/webapp/yarn.lock +++ b/src/webapp/yarn.lock @@ -1085,6 +1085,10 @@ braces@^1.8.2: preserve "^0.2.0" repeat-element "^1.1.2" +brcast@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/brcast/-/brcast-3.0.1.tgz#6256a8349b20de9eed44257a9b24d71493cd48dd" + brorand@^1.0.1: version "1.1.0" resolved "https://registry.yarnpkg.com/brorand/-/brorand-1.1.0.tgz#12c25efe40a45e3c323eb8675a0a0ce57b22371f" @@ -1682,6 +1686,12 @@ css-selector-tokenizer@^0.7.0: fastparse "^1.1.1" regexpu-core "^1.0.0" +css-vendor@^0.3.8: + version "0.3.8" + resolved "https://registry.yarnpkg.com/css-vendor/-/css-vendor-0.3.8.tgz#6421cfd3034ce664fe7673972fd0119fc28941fa" + dependencies: + is-in-browser "^1.0.2" + css-what@2.1: version "2.1.0" resolved "https://registry.yarnpkg.com/css-what/-/css-what-2.1.0.tgz#9467d032c38cfaefb9f2d79501253062f87fa1bd" @@ -2993,7 +3003,7 @@ hoek@4.x.x: version "4.2.1" resolved "https://registry.yarnpkg.com/hoek/-/hoek-4.2.1.tgz#9634502aa12c445dd5a7c5734b572bb8738aacbb" -hoist-non-react-statics@^2.3.0, hoist-non-react-statics@^2.5.0: +hoist-non-react-statics@^2.3.0, hoist-non-react-statics@^2.3.1, hoist-non-react-statics@^2.5.0: version "2.5.0" resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-2.5.0.tgz#d2ca2dfc19c5a91c5a6615ce8e564ef0347e2a40" @@ -3123,6 +3133,10 @@ https-browserify@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/https-browserify/-/https-browserify-1.0.0.tgz#ec06c10e0a34c0f2faf199f7fd7fc78fffd03c73" +hyphenate-style-name@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/hyphenate-style-name/-/hyphenate-style-name-1.0.2.tgz#31160a36930adaf1fc04c6074f7eb41465d4ec4b" + iconv-lite@0.4.19, iconv-lite@^0.4.17, iconv-lite@~0.4.13: version "0.4.19" resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.19.tgz#f7468f60135f5e5dad3399c0a81be9a1603a082b" @@ -3320,6 +3334,10 @@ is-fullwidth-code-point@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" +is-function@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-function/-/is-function-1.0.1.tgz#12cfb98b65b57dd3d193a3121f5f6e2f437602b5" + is-glob@^2.0.0, is-glob@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-2.0.1.tgz#d096f926a3ded5600f3fdfd91198cb0888c2d863" @@ -3332,6 +3350,10 @@ is-glob@^3.1.0: dependencies: is-extglob "^2.1.0" +is-in-browser@^1.0.2, is-in-browser@^1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/is-in-browser/-/is-in-browser-1.1.3.tgz#56ff4db683a078c6082eb95dad7dc62e1d04f835" + is-installed-globally@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/is-installed-globally/-/is-installed-globally-0.1.0.tgz#0dfd98f5a9111716dd535dda6492f67bf3d25a80" @@ -3379,6 +3401,12 @@ is-plain-obj@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-1.1.0.tgz#71a50c8429dfca773c92a390a4a03b39fcd51d3e" +is-plain-object@^2.0.1: + version "2.0.4" + resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677" + dependencies: + isobject "^3.0.1" + is-posix-bracket@^0.1.0: version "0.1.1" resolved "https://registry.yarnpkg.com/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz#3334dc79774368e92f016e6fbc0a88f5cd6e6bc4" @@ -3461,6 +3489,10 @@ isobject@^2.0.0: dependencies: isarray "1.0.0" +isobject@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df" + isomorphic-fetch@^2.1.1: version "2.2.1" resolved "https://registry.yarnpkg.com/isomorphic-fetch/-/isomorphic-fetch-2.2.1.tgz#611ae1acf14f5e81f729507472819fe9733558a9" @@ -3859,6 +3891,81 @@ jsprim@^1.2.2: json-schema "0.2.3" verror "1.10.0" +jss-camel-case@^6.1.0: + version "6.1.0" + resolved "https://registry.yarnpkg.com/jss-camel-case/-/jss-camel-case-6.1.0.tgz#ccb1ff8d6c701c02a1fed6fb6fb6b7896e11ce44" + dependencies: + hyphenate-style-name "^1.0.2" + +jss-compose@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/jss-compose/-/jss-compose-5.0.0.tgz#ce01b2e4521d65c37ea42cf49116e5f7ab596484" + dependencies: + warning "^3.0.0" + +jss-default-unit@^8.0.2: + version "8.0.2" + resolved "https://registry.yarnpkg.com/jss-default-unit/-/jss-default-unit-8.0.2.tgz#cc1e889bae4c0b9419327b314ab1c8e2826890e6" + +jss-expand@^5.1.0: + version "5.1.0" + resolved "https://registry.yarnpkg.com/jss-expand/-/jss-expand-5.1.0.tgz#b1ad74ec18631f34f65a2124fcfceb6400610e3d" + +jss-extend@^6.2.0: + version "6.2.0" + resolved "https://registry.yarnpkg.com/jss-extend/-/jss-extend-6.2.0.tgz#4af09d0b72fb98ee229970f8ca852fec1ca2a8dc" + dependencies: + warning "^3.0.0" + +jss-global@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/jss-global/-/jss-global-3.0.0.tgz#e19e5c91ab2b96353c227e30aa2cbd938cdaafa2" + +jss-nested@^6.0.1: + version "6.0.1" + resolved "https://registry.yarnpkg.com/jss-nested/-/jss-nested-6.0.1.tgz#ef992b79d6e8f63d939c4397b9d99b5cbbe824ca" + dependencies: + warning "^3.0.0" + +jss-preset-default@^4.3.0: + version "4.3.0" + resolved "https://registry.yarnpkg.com/jss-preset-default/-/jss-preset-default-4.3.0.tgz#7bc91b0b282492557d36ed4e5c6d7c8cb3154bb8" + dependencies: + jss-camel-case "^6.1.0" + jss-compose "^5.0.0" + jss-default-unit "^8.0.2" + jss-expand "^5.1.0" + jss-extend "^6.2.0" + jss-global "^3.0.0" + jss-nested "^6.0.1" + jss-props-sort "^6.0.0" + jss-template "^1.0.1" + jss-vendor-prefixer "^7.0.0" + +jss-props-sort@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/jss-props-sort/-/jss-props-sort-6.0.0.tgz#9105101a3b5071fab61e2d85ea74cc22e9b16323" + +jss-template@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/jss-template/-/jss-template-1.0.1.tgz#09aed9d86cc547b07f53ef355d7e1777f7da430a" + dependencies: + warning "^3.0.0" + +jss-vendor-prefixer@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/jss-vendor-prefixer/-/jss-vendor-prefixer-7.0.0.tgz#0166729650015ef19d9f02437c73667231605c71" + dependencies: + css-vendor "^0.3.8" + +jss@^9.3.2: + version "9.8.0" + resolved "https://registry.yarnpkg.com/jss/-/jss-9.8.0.tgz#77830def563870103f8671ed31ce3a3d2f32aa2b" + dependencies: + is-in-browser "^1.1.3" + symbol-observable "^1.1.0" + warning "^3.0.0" + jsx-ast-utils@^1.4.0: version "1.4.1" resolved "https://registry.yarnpkg.com/jsx-ast-utils/-/jsx-ast-utils-1.4.1.tgz#3867213e8dd79bf1e8f2300c0cfc1efb182c0df1" @@ -5050,6 +5157,14 @@ prop-types-extra@^1.0.1: dependencies: warning "^3.0.0" +prop-types@15.x: + version "15.6.1" + resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.6.1.tgz#36644453564255ddda391191fb3a125cbdf654ca" + dependencies: + fbjs "^0.8.16" + loose-envify "^1.3.1" + object-assign "^4.1.1" + prop-types@^15.5.10, prop-types@^15.5.4, prop-types@^15.5.6, prop-types@^15.5.8, prop-types@^15.6.0: version "15.6.0" resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.6.0.tgz#ceaf083022fc46b4a35f69e13ef75aed0d639856" @@ -5191,6 +5306,15 @@ react-bootstrap@^0.32.1: uncontrollable "^4.1.0" warning "^3.0.0" +react-bs-notifier@^4.4.6: + version "4.4.6" + resolved "https://registry.yarnpkg.com/react-bs-notifier/-/react-bs-notifier-4.4.6.tgz#7a176f4ebf708c11022e2f9460583152751d74ac" + dependencies: + prop-types "15.x" + react-jss ">= 8 <9" + react-transition-group "2.x" + toetag "3.x" + react-dev-utils@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/react-dev-utils/-/react-dev-utils-5.0.0.tgz#425ac7c9c40c2603bc4f7ab8836c1406e96bb473" @@ -5233,6 +5357,16 @@ react-fontawesome@^1.6.1: dependencies: prop-types "^15.5.6" +"react-jss@>= 8 <9": + version "8.3.3" + resolved "https://registry.yarnpkg.com/react-jss/-/react-jss-8.3.3.tgz#677a57569d3e4f5099fcdeafeddd8d2c62ab5977" + dependencies: + hoist-non-react-statics "^2.3.1" + jss "^9.3.2" + jss-preset-default "^4.3.0" + prop-types "^15.6.0" + theming "^1.3.0" + react-overlays@^0.8.0: version "0.8.3" resolved "https://registry.yarnpkg.com/react-overlays/-/react-overlays-0.8.3.tgz#fad65eea5b24301cca192a169f5dddb0b20d3ac5" @@ -5334,7 +5468,7 @@ react-scripts@1.1.1: optionalDependencies: fsevents "^1.1.3" -react-transition-group@^2.0.0, react-transition-group@^2.2.0: +react-transition-group@2.x, react-transition-group@^2.0.0, react-transition-group@^2.2.0: version "2.2.1" resolved "https://registry.yarnpkg.com/react-transition-group/-/react-transition-group-2.2.1.tgz#e9fb677b79e6455fd391b03823afe84849df4a10" dependencies: @@ -6146,7 +6280,7 @@ sw-toolbox@^3.4.0: path-to-regexp "^1.0.1" serviceworker-cache-polyfill "^4.0.0" -symbol-observable@^1.0.3: +symbol-observable@^1.0.3, symbol-observable@^1.1.0: version "1.2.0" resolved "https://registry.yarnpkg.com/symbol-observable/-/symbol-observable-1.2.0.tgz#c22688aed4eab3cdc2dfeacbb561660560a00804" @@ -6210,6 +6344,15 @@ text-table@0.2.0, text-table@~0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" +theming@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/theming/-/theming-1.3.0.tgz#286d5bae80be890d0adc645e5ca0498723725bdc" + dependencies: + brcast "^3.0.1" + is-function "^1.0.1" + is-plain-object "^2.0.1" + prop-types "^15.5.8" + throat@^3.0.0: version "3.2.0" resolved "https://registry.yarnpkg.com/throat/-/throat-3.2.0.tgz#50cb0670edbc40237b9e347d7e1f88e4620af836" @@ -6254,6 +6397,10 @@ to-fast-properties@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/to-fast-properties/-/to-fast-properties-1.0.3.tgz#b83571fa4d8c25b82e231b06e3a3055de4ca1a47" +toetag@3.x: + version "3.3.7" + resolved "https://registry.yarnpkg.com/toetag/-/toetag-3.3.7.tgz#cec33c097acedb97e7a59c519887d8ad5adff2c6" + toposort@^1.0.0: version "1.0.6" resolved "https://registry.yarnpkg.com/toposort/-/toposort-1.0.6.tgz#c31748e55d210effc00fdcdc7d6e68d7d7bb9cec" From 8219e39c2b517f2e2ef76ff38a84a593228c5442 Mon Sep 17 00:00:00 2001 From: Liu Chao Date: Tue, 27 Feb 2018 17:19:34 +0800 Subject: [PATCH 32/54] Enable to toggle diary permission --- src/webapp/src/actions.js | 93 ++++++++++++++++++---------- src/webapp/src/components/Diaries.js | 35 ++++++++--- src/webapp/src/components/Home.js | 16 ++--- src/webapp/src/components/Logout.js | 4 ++ src/webapp/src/reducers.js | 81 +++++++++++------------- 5 files changed, 135 insertions(+), 94 deletions(-) diff --git a/src/webapp/src/actions.js b/src/webapp/src/actions.js index 573c749..7ab9b09 100644 --- a/src/webapp/src/actions.js +++ b/src/webapp/src/actions.js @@ -5,20 +5,21 @@ import API_Endpoints from './utils/API_Endpoints'; export const REQUEST_MEMBERS = 'REQUEST_MEMBERS'; export const RECEIVE_MEMBERS = 'RECEIVE_MEMBERS'; export const REQUEST_PUBLIC_DIARIES = 'REQUEST_PUBLIC_DIARIES'; -export const RECEIVE_PUBLIC_DIARIES = 'RECEIVE_PUBLIC_DIARIES'; export const REQUEST_MY_DIARIES = 'REQUEST_MY_DIARIES'; -export const RECEIVE_MY_DIARIES = 'RECEIVE_MY_DIARIES'; +export const RECEIVE_DIARIES = 'RECEIVE_DIARIES'; +export const REMOVE_DIARY = 'REMOVE_DIARY'; export const REQUEST_USER = 'REQUEST_USER'; export const RECEIVE_USER = 'RECEIVE_USER'; -export const HANDLE_AUTH_ERR = 'HANDLE_AUTH_ERR'; export const UNAUTHENTICATE_USER = 'UNAUTHENTICATE_USER'; -export const REMOVE_DIARY = 'REMOVE_DIARY'; +export const HANDLE_AUTH_ERR = 'HANDLE_AUTH_ERR'; export const SHOW_ALERT = 'SHOW_ALERT'; export const DISMISS_ALERT = 'DISMISS_ALERT'; +export const TOGGLE_PERMISSION = 'TOGGLE_PERMISSION'; -function requestMembers() { +function requestMembers(isFetching) { return { - type: REQUEST_MEMBERS + type: REQUEST_MEMBERS, + isFetching }; } @@ -29,40 +30,35 @@ function receiveMembers(items) { }; } -function requestPublicDiaires() { +function requestPublicDiaires(isFetching) { return { - type: REQUEST_PUBLIC_DIARIES - }; -} - -function receivePublicDiaries(items) { - return { - type: RECEIVE_PUBLIC_DIARIES, - diaries: items + type: REQUEST_PUBLIC_DIARIES, + isFetching }; } -function requestMyDiaries() { +function requestMyDiaries(isFetching) { return { - type: REQUEST_MY_DIARIES + type: REQUEST_MY_DIARIES, + isFetching }; } -function receiveMyDiaries(items) { +function receiveDiaries(items) { return { - type: RECEIVE_MY_DIARIES, + type: RECEIVE_DIARIES, diaries: items }; } -function requestItems(type) { +function requestItems(type, isFetching = true) { switch (type) { case 'members': - return requestMembers(); + return requestMembers(isFetching); case 'public-diaries': - return requestPublicDiaires(); + return requestPublicDiaires(isFetching); case 'my-diaries': - return requestMyDiaries(); + return requestMyDiaries(isFetching); } } @@ -71,9 +67,8 @@ function receiveItems(type, items) { case 'members': return receiveMembers(items); case 'public-diaries': - return receivePublicDiaries(items); case 'my-diaries': - return receiveMyDiaries(items); + return receiveDiaries(items); } } @@ -97,7 +92,11 @@ export function fetchItems(type) { } else { promise = ajax_get(getUrl(type)); } - return promise.then(data => dispatch(receiveItems(type, data.result))); + return promise + .then(data => dispatch(receiveItems(type, data.result))) + .finally(() => { + dispatch(requestItems(type, false)); + }); }; } @@ -201,13 +200,6 @@ export function checkIsAuthenticated() { }; } -function removeDiary(diary) { - return { - type: REMOVE_DIARY, - diary - }; -} - export function showAlert(alert) { return { type: SHOW_ALERT, @@ -222,6 +214,13 @@ export function dismissAlert(alert) { }; } +function removeDiary(diary) { + return { + type: REMOVE_DIARY, + diary + }; +} + export function deleteDiary(diary) { return dispatch => { dispatch(removeDiary(diary)); @@ -250,3 +249,31 @@ export function deleteDiary(diary) { }); }; } + +function toggleDiaryPermission(diary) { + return { + type: TOGGLE_PERMISSION, + diary + }; +} + +export function togglePermission(diary) { + return dispatch => { + dispatch(toggleDiaryPermission(diary)); + return ajax_post( + API_Endpoints.toggle_diary_permission, + { + id: diary.id, + public: !diary.public + }, + true + ).catch(error => { + dispatch( + showAlert({ + type: 'danger', + message: error + }) + ); + }); + }; +} diff --git a/src/webapp/src/components/Diaries.js b/src/webapp/src/components/Diaries.js index e1a1b0c..4b4a0a0 100644 --- a/src/webapp/src/components/Diaries.js +++ b/src/webapp/src/components/Diaries.js @@ -9,11 +9,17 @@ import { Row } from 'react-bootstrap'; import { connect } from 'react-redux'; -import { deleteDiary } from '../actions'; +import { deleteDiary, togglePermission } from '../actions'; class Diaries extends Component { render() { - const { isLoading, diaries, deleteDiary } = this.props; + const { + isAuthenticated, + isLoading, + diaries, + deleteDiary, + toggleDiary + } = this.props; if (isLoading) { return ( @@ -33,9 +39,7 @@ class Diaries extends Component {

    {diary.text}

    - {diary.public ? ( - '' - ) : ( + {isAuthenticated ? ( + + ) : ( + '' )} @@ -60,10 +72,19 @@ class Diaries extends Component { } } +function mapStateToProps(state) { + const { account } = state; + const { isAuthenticated } = account; + return { + isAuthenticated + }; +} + function mapDispatchToProps(dispatch) { return { - deleteDiary: diary => dispatch(deleteDiary(diary)) + deleteDiary: diary => dispatch(deleteDiary(diary)), + toggleDiary: diary => dispatch(togglePermission(diary)) }; } -export default connect(null, mapDispatchToProps)(Diaries); +export default connect(mapStateToProps, mapDispatchToProps)(Diaries); diff --git a/src/webapp/src/components/Home.js b/src/webapp/src/components/Home.js index b69fd8d..b6a25bc 100644 --- a/src/webapp/src/components/Home.js +++ b/src/webapp/src/components/Home.js @@ -83,17 +83,17 @@ class Home extends Component { function mapStateToProps(state) { const { members: allMembers, - publicDiaries: allPublicDiaries, - myDiaries: allMyDiaries, + isLoadingPublicDiaries, + isLoadingMyDiaries, + allDiaries, account } = state; - const { isFetching: isLoadingMembers, items: members } = allMembers; - const { - isFetching: isLoadingPublicDiaries, - items: publicDiaries - } = allPublicDiaries; - const { isFetching: isLoadingMyDiaries, items: myDiaries } = allMyDiaries; const { isAuthenticated } = account; + const { isFetching: isLoadingMembers, items: members } = allMembers; + + const publicDiaries = allDiaries.filter(diary => diary.public); + const myDiaries = allDiaries.filter(diary => !diary.public); + return { isAuthenticated, isLoadingMembers, diff --git a/src/webapp/src/components/Logout.js b/src/webapp/src/components/Logout.js index 4d73abf..f1a9a13 100644 --- a/src/webapp/src/components/Logout.js +++ b/src/webapp/src/components/Logout.js @@ -19,6 +19,10 @@ class Logout extends Component { {isLoading ? ( 'Loading...' + ) : isAuthenticated ? ( + + Something went wrong. Please refresh your page. + ) : ( You are logged out successfully. )} diff --git a/src/webapp/src/reducers.js b/src/webapp/src/reducers.js index 0d2acca..f5161c5 100644 --- a/src/webapp/src/reducers.js +++ b/src/webapp/src/reducers.js @@ -3,16 +3,16 @@ import { REQUEST_MEMBERS, RECEIVE_MEMBERS, REQUEST_PUBLIC_DIARIES, - RECEIVE_PUBLIC_DIARIES, REQUEST_MY_DIARIES, - RECEIVE_MY_DIARIES, + RECEIVE_DIARIES, + REMOVE_DIARY, REQUEST_USER, RECEIVE_USER, - HANDLE_AUTH_ERR, UNAUTHENTICATE_USER, - REMOVE_DIARY, + HANDLE_AUTH_ERR, SHOW_ALERT, - DISMISS_ALERT + DISMISS_ALERT, + TOGGLE_PERMISSION } from './actions'; function members( @@ -25,11 +25,10 @@ function members( switch (action.type) { case REQUEST_MEMBERS: return Object.assign({}, state, { - isFetching: true + isFetching: action.isFetching }); case RECEIVE_MEMBERS: return Object.assign({}, state, { - isFetching: false, items: action.members }); default: @@ -37,62 +36,51 @@ function members( } } -function removeDiary(state = [], action) { +function isLoadingPublicDiaries(state = true, action) { switch (action.type) { - case REMOVE_DIARY: - const { diary } = action; - const index = state.indexOf(diary); - return [...state.slice(0, index), ...state.slice(index + 1)]; + case REQUEST_PUBLIC_DIARIES: + return action.isFetching; + default: + return state; } } -function publicDiaries( - state = { - isFetching: false, - items: [] - }, - action -) { +function isLoadingMyDiaries(state = true, action) { switch (action.type) { - case REQUEST_PUBLIC_DIARIES: - return Object.assign({}, state, { - isFetching: true - }); - case RECEIVE_PUBLIC_DIARIES: - return Object.assign({}, state, { - isFetching: false, - items: action.diaries - }); - case REMOVE_DIARY: - return Object.assign({}, state, { - items: removeDiary(state.items, action) - }); + case REQUEST_MY_DIARIES: + return action.isFetching; default: return state; } } -function myDiaries( +function diary( state = { - isFetching: false, - items: [] + title: '', + text: '', + public: true }, action ) { switch (action.type) { - case REQUEST_MY_DIARIES: + case TOGGLE_PERMISSION: return Object.assign({}, state, { - isFetching: true + public: !state.public }); - case RECEIVE_MY_DIARIES: - return Object.assign({}, state, { - isFetching: false, - items: action.diaries + } +} + +function allDiaries(state = [], action) { + switch (action.type) { + case RECEIVE_DIARIES: + return [...state, ...action.diaries]; + case TOGGLE_PERMISSION: + return state.map(d => { + return d.id === action.diary.id ? diary(action.diary, action) : d; }); case REMOVE_DIARY: - return Object.assign({}, state, { - items: removeDiary(state.items, action) - }); + const index = state.indexOf(action.diary); + return [...state.slice(0, index), ...state.slice(index + 1)]; default: return state; } @@ -150,8 +138,9 @@ function alerts(state = [], action) { const rootReducer = combineReducers({ members, - publicDiaries, - myDiaries, + isLoadingPublicDiaries, + isLoadingMyDiaries, + allDiaries, account, alerts }); From 6b04d38aedbb48f5b7c8224408d472be25b69559 Mon Sep 17 00:00:00 2001 From: Liu Chao Date: Tue, 27 Feb 2018 17:53:36 +0800 Subject: [PATCH 33/54] Enable to set public when creating new diary --- src/service/app.py | 2 +- src/webapp/package.json | 1 + src/webapp/src/App.js | 2 +- src/webapp/src/components/NewDiary.js | 14 +++++++++++++- src/webapp/src/reducers.js | 3 ++- 5 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/service/app.py b/src/service/app.py index e7ee872..3fe2509 100644 --- a/src/service/app.py +++ b/src/service/app.py @@ -126,7 +126,7 @@ def get_secret_diary(): curr_token = request.json.get('token') target = session.query(Token).filter_by(uuid=curr_token).first() if target and not target.expired: - diaryList = session.query(Diary).filter_by(author=target.username) + diaryList = session.query(Diary).filter_by(author=target.username, public=False) diaryList_serialized = [d.serialize for d in diaryList.all()] return jsonify({'status': True, 'result':diaryList_serialized}), 201# return jsonify({'status': False, 'error': 'Invalid authentication token.'}), 200# diff --git a/src/webapp/package.json b/src/webapp/package.json index 0c33a4f..0308c98 100644 --- a/src/webapp/package.json +++ b/src/webapp/package.json @@ -6,6 +6,7 @@ "bootstrap": "3", "cross-fetch": "^1.1.1", "font-awesome": "^4.7.0", + "lodash": "^4.17.5", "react": "^16.2.0", "react-bootstrap": "^0.32.1", "react-bs-notifier": "^4.4.6", diff --git a/src/webapp/src/App.js b/src/webapp/src/App.js index 6240563..55424e3 100644 --- a/src/webapp/src/App.js +++ b/src/webapp/src/App.js @@ -2,7 +2,7 @@ import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; import { Home, Login, Signup, Account, NewDiary, Logout } from './components'; import { Navbar, Nav, NavItem, Grid, Row, Col } from 'react-bootstrap'; -import { Button, LinkContainer } from 'react-router-bootstrap'; +import { LinkContainer } from 'react-router-bootstrap'; import { connect } from 'react-redux'; import { checkIsAuthenticated, logout, dismissAlert } from './actions'; import { Alert, AlertContainer } from 'react-bs-notifier'; diff --git a/src/webapp/src/components/NewDiary.js b/src/webapp/src/components/NewDiary.js index 17bfa90..ee5317a 100644 --- a/src/webapp/src/components/NewDiary.js +++ b/src/webapp/src/components/NewDiary.js @@ -3,6 +3,7 @@ import ajax_post from '../utils/ajax_post'; import API_Endpoints from '../utils/API_Endpoints'; import { Alert, + Checkbox, Form, FormGroup, FormControl, @@ -35,6 +36,7 @@ class NewDiary extends Component { e.preventDefault(); const title = (this.titleField.value || '').trim(); const text = (this.textField.value || '').trim(); + const isPublic = this.publicField.checked; if (!title) { this.setError('Title is required'); @@ -49,7 +51,7 @@ class NewDiary extends Component { { title, text, - public: false + public: isPublic }, true ) @@ -95,6 +97,16 @@ class NewDiary extends Component { /> + + +   + + + (this.publicField = ref)}> + Is Public + + +