def updatePassword(): data = json.loads(request.data) currentPassword = data["currentPassword"] newPassword = data["newPassword"] confirmNewPassword = data["confirmNewPassword"] if not UserModel.checkPassword(getCurrentUid(), currentPassword): return json.dumps({ "result": "fail", "msg": "Current password is not correct!" }) if newPassword != confirmNewPassword: return json.dumps({"result": "fail", "msg": "Passwords don't match!"}) if not isValidPassword(newPassword): return json.dumps({ "result": "fail", "msg": "Password is not valid! It must be at least 6 characters." }) UserModel.updatePassword(getCurrentUid(), newPassword) return json.dumps({ "result": "success", "msg": "Password has updated successfully!" })
def updateUsername(): data = json.loads(request.data) newUsername = data["username"] password = data["password"] if not UserModel.checkPassword(getCurrentUid(), password): return json.dumps({ "result": "fail", "msg": "Password is not correct!" }) if not isValidUsername(newUsername): return json.dumps({ "result": "fail", "msg": "Username is not valid! It should be at least 1 character alpha-numeric and can contain '-', '_'" }) if newUsername != None and newUsername != "": UserModel.updateUsername(getCurrentUid(), newUsername) return json.dumps({ "result": "success", "msg": "Username successfully updated!" }) else: return json.dumps({ "result": "fail", "msg": "You have to enter username to update it." })
def updateEmail(): data = json.loads(request.data) newEmail = data["email"] password = data["password"] if not UserModel.checkPassword(getCurrentUid(), password): return json.dumps({ "result": "fail", "msg": "Password is not correct!" }) if not isValidEmail(newEmail): return json.dumps({ "result": "fail", "msg": "Please enter a valid email!" }) if getCurrentUser()["email"] == newEmail: return json.dumps({ "result": "fail", "msg": "This is your current email!" }) UserModel.updateEmail(getCurrentUid(), newEmail) return json.dumps({ "result": "success", "msg": "Email updated! You should activate your new email clicking the activation link we've sent you." })
def userPhoto(uid): try: uid = int(uid) except ValueError: uid = getCurrentUid() user = UserModel.getUser(uid) if request.method == "POST": size = len(request.data) / 1000000 if size > 2: return json.dumps({ "result": "fail", "msg": "File can not be more than 2 MB" }) newFileName = str(uid) + "_" + generateCode(10) + ".jpg" with open(UPLOAD_FOLDER + "/users/up/" + newFileName, "wb") as fh: fh.write(request.data) UserModel.updateProfilePhoto(getCurrentUid(), newFileName) #Delete old uploaded file if user["photo"] != None: try: os.remove(UPLOAD_FOLDER + "/users/up/" + user["photo"]) except: print("File couldn't be removed!") return json.dumps({"result": "success"}) return json.dumps({"result": "fail"})
def login(): if not isLoggedIn(): if request.method == "POST": #User Login email = request.form.get("email") password = request.form.get("password") if (UserModel.login(email, password)): user = UserModel.getUserByEmail(email) if user["isEmailVerified"]: createSession(email) return redirect(url_for("index")) else: flash(""" You didn't activate your email address. Please activate your email address. If you didn't receive an email, <a href="/send-verification-mail/{}">click here.</a> """.format(email)) return redirect(url_for("login")) else: flash("Email or password is not correct") return redirect(url_for("login")) else: return render_template("intro/login.html") else: return redirect(url_for("index"))
def userProfile(username): currentUser = getCurrentUser() user = UserModel.getUserByUsername(username, getCurrentUid()) if user == None: return render_template("not-found.html", title="User Not Found!", msg="The user you trying to access not found!", currentUser=getCurrentUser()) userLinks = UserModel.getUserLinks(user["uid"]) userProjects = ProjectModel.getUserProjects(user["uid"]) lastUserPosts = UserPostModel.getLastUserPosts(user["uid"], 10, getCurrentUid()) popularProjects = ProjectModel.getPopularProjects(10) whoToFollowList = UserModel.getWhoToFollowList(5, getCurrentUid()) #Remove password and email fields user.pop("password") user.pop("email") return render_template("user-profile.html", currentUser=currentUser, user=user, userLinks=userLinks, userProjects=userProjects, lastUserPosts=lastUserPosts, popularProjects=popularProjects, whoToFollowList=whoToFollowList)
def userBio(): bio = json.loads(request.data)["bio"] bio.strip() if bio != "": UserModel.updateBio(getCurrentUid(), bio) return json.dumps({"result": "success"}) else: return json.dumps({"result": "fail"})
def userFullName(): fullname = request.args.get("full-name") if fullname != None: fullname.strip() if fullname != "": UserModel.updateFullname(getCurrentUid(), fullname) return json.dumps({"result": "success"}) else: return json.dumps({"result": "fail"})
def emailVerify(): if request.method == "GET": email = request.args.get("email") hashCode = request.args.get("hash") if email != None and UserModel.isThereThisEmail(email) and hashCode != None: if hashCode == generateEmailVerificationHashCode(email): UserModel.verifyEmail(email) flash("Your email address verified successfully!", "success") return redirect(url_for("login")) return redirect(url_for("index"))
def projectPage(projectName): currentUser = getCurrentUser() project = ProjectModel.getProjectByProjectName(projectName) if project == None: return render_template( "not-found.html", title = "Project Not Found!", msg = "The project you trying to access not found!", currentUser = getCurrentUser() ) projectLinks = ProjectModel.getProjectLinks(project["pid"]) lastProjectPosts = ProjectPostModel.getLastProjectPosts(project["pid"], 10, getCurrentUid()) numberOfMembers = ProjectModel.getNumberOfMembers(project["pid"]) numberOfEmptySeaters = SeaterModel.getProjectEmptySeaterNumber(project["pid"]) popularProjects = ProjectModel.getPopularProjects(10) whoToFollowList = UserModel.getWhoToFollowList(5, getCurrentUid()) return render_template( "project-page.html", currentUser = currentUser, project = project, projectLinks = projectLinks, lastProjectPosts = lastProjectPosts, numberOfMembers = numberOfMembers, numberOfEmptySeaters = numberOfEmptySeaters, popularProjects = popularProjects, whoToFollowList = whoToFollowList )
def isThereThisUsername(username): data = dict() if UserModel.isThereThisUsername(username): data["result"] = True else: data["result"] = False return json.dumps(data)
def sitemap(): lastUsers = UserModel.getLastUsers(500) lastProjects = ProjectModel.getLastProjects(500) return render_template("sitemap.xml", lastUsers=lastUsers, lastProjects=lastProjects, SITE_ADDR=SITE_ADDR)
def isGlobalAdmin(uid): data = dict() if UserModel.isGlobalAdmin(uid): data["result"] = True else: data["result"] = False return json.dumps(data)
def isThereThisEmail(email): data = dict() if UserModel.isThereThisEmail(email): data["result"] = True else: data["result"] = False return json.dumps(data)
def generalSearch(query): userResults = UserModel.searchUsers(query, 5) projectResults = ProjectModel.searchProjects(query, 5) return json.dumps( { "userResults": userResults, "projectResults": projectResults }, cls=DateTimeEncoder)
def passwordReset(): if request.method == "POST": email = request.form.get("email") hashCodeFromUser = request.form.get("hash") password = request.form.get("password") confirmPassword = request.form.get("confirm-password") if email != None and UserModel.isThereThisEmail(email): hashCode = generatePasswordResetHashCode(email) if hashCodeFromUser != None and password != None and confirmPassword != None: if hashCode == hashCodeFromUser and password == confirmPassword: #Get user id userId = UserModel.getUserByEmail(email)["uid"] #Update password UserModel.updatePassword(userId, password) flash("Your password updated succesfully. Now you can log in.", "success") return redirect(url_for("login")) else: #Send password reset mail sendMail({ "To" : email, "Subject" : "Password Reset - devSeater", "Body" : render_template("mail/password-reset-mail.html", SITE_ADDR = SITE_ADDR, email = email, hashCode = hashCode) }) #Show message flash("If you have entered your email address properly, we sent you an email. Please check your inbox.", "success") else: return redirect(url_for("index")) return redirect(url_for("passwordReset")) else: email = request.args.get("email") hashCode = request.args.get("hash") return render_template("intro/password-reset.html", email = email, hashCode = hashCode)
def seaterPage(projectName, sid): project = ProjectModel.getProjectByProjectName(projectName) seater = SeaterModel.getSeater(sid, getCurrentUid()) seater["skills"] = SkillModel.getSeaterSkills(sid) assignedUser = UserModel.getUser(seater["uid"]) seater["isProjectAdmin"] = ProjectModel.isProjectAdmin(getCurrentUid(), project["pid"]) return render_template( "seater-page.html", currentUser= getCurrentUser(), seater = seater, assignedUser = assignedUser )
def getUser(): if request.method == "GET": uid = request.args.get("uid") username = request.args.get("username") email = request.args.get("email") if uid != None: user = UserModel.getUser(uid) elif username != None: user = UserModel.getUserByUsername(username) elif email != None: user = UserModel.getUserByEmail(email) else: return render_template("private-api/unknown-request.html") try: user.pop("password") except: print("password field cannot be popped!") return return json.dumps(user, cls=DateTimeEncoder) return redirect(url_for("index"))
def userLinks(): if request.method == "GET": uid = request.args.get("uid") if uid == None: uid = getCurrentUid() #Getting all user's links links = UserModel.getUserLinks(uid) return json.dumps(links, cls=DateTimeEncoder) elif request.method == "POST": #Stripping data = json.loads(request.data) data["name"] = data["name"].strip() data["link"] = data["link"].strip() #Adding new user link if data["name"] != "" and data["link"] != "": ulid = UserModel.addUserLink(getCurrentUid(), data["name"], data["link"]) return json.dumps({"result": "success", "ulid": ulid}) elif request.method == "PUT": #Updating a user link data = json.loads(request.data) ulid = request.args.get("ulid") link = UserModel.getUserLink(ulid) if link["uid"] == getCurrentUid(): UserModel.updateUserLink(ulid, data["name"], data["link"]) return json.dumps({"result": "success"}) else: return render_template("private-api/forbidden-request.html") else: #Delete a user link #DELETE request ulid = request.args.get("ulid") link = UserModel.getUserLink(ulid) if link["uid"] == getCurrentUid(): UserModel.removeUserLink(ulid) return json.dumps({"result": "success"}) else: return render_template("private-api/forbidden-request.html") return render_template("private-api/unknown-request.html")
def unfollow(uid): UserModel.unFollow(getCurrentUid(), uid) return json.dumps({"result": "success"})
def generatePasswordResetHashCode(email): user = UserModel.getUserByEmail(email) h = hashlib.sha256() stringToHash = user["email"] + user["password"] + user["full_name"] + user["username"] h.update(stringToHash.encode("utf-8")) return h.hexdigest()
def checkUsernameAvailability(username): return json.dumps({"result": not UserModel.isThereThisUsername(username)})
def index(): if not isLoggedIn(): if request.method == "POST": # USER REGISTRATION email = request.form.get("email").strip() name = request.form.get("name").strip() username = request.form.get("username").strip() password = request.form.get("password").strip() terms = request.form.get("terms") #Validate all values errorMessages = dict() if (not isValidEmail(email)): errorMessages["email"] = "Please enter a valid email address" elif (UserModel.isThereThisEmail(email)): errorMessages["email"] = "This email address is already taken" if (len(name) < 3): errorMessages["name"] = "Name should be at least 3 characters" if (not isValidUsername(username)): errorMessages[ "username"] = "******" elif (UserModel.isThereThisUsername(username)): errorMessages["username"] = "******" if not isValidPassword(password): errorMessages[ "password"] = "******" if (terms != "on"): errorMessages["terms"] = "You should accept terms" if (not errorMessages): UserModel.addUser({ "email": email, "username": username, "full_name": name, "password": password }) sendVerificationEmail(email) flash( "User created successfully, please check your inbox for email verification", "success") return redirect(url_for("login")) else: return render_template("intro/intro.html", form=request.form, errorMessages=errorMessages) else: return render_template("intro/intro.html") else: #Logged In #Get User Projects userProjects = ProjectModel.getUserProjects(session["uid"]) lastFollowingPosts = UserPostModel.getLastFollowingPosts( session["uid"], 10) popularProjects = ProjectModel.getPopularProjects(10) whoToFollowList = UserModel.getWhoToFollowList(5, getCurrentUid()) #Get Current User Informations currentUser = UserModel.getUser(session["uid"]) return render_template("index.html", userProjects=userProjects, popularProjects=popularProjects, lastFollowingPosts=lastFollowingPosts, currentUser=currentUser, whoToFollowList=whoToFollowList)