def authed(): try: #if bool(session.get("id", False)): # return True pemfile = open("/jwt.pub", 'r') keystring = pemfile.read() pemfile.close() decoded = jwt.decode(request.headers.get('X-CTFProxy-JWT'), keystring, algorithm='EdDSA') username = decoded['username'].decode('utf-8') displayname = decoded['displayname'].decode('utf-8') groups = [x.split("@")[0] for x in decoded['groups']] user = Users.query.filter_by(email=username).first() if user is not None: session["id"] = user.id user.name = displayname user.email = username user.affiliation = ",".join(groups) user.type = "admin" if "ctfd-admin" in groups else "user" db.session.commit() db.session.flush() else: user = Users( name=displayname, email=username, verified=True, affiliation=",".join(groups), type="admin" if "ctfd-admin" in groups else "user", ) db.session.add(user) db.session.commit() db.session.flush() session["id"] = user.id return True except: return False
def oauth_redirect(): os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' if request.values.get('error'): log("logins", "[{date}] {ip} - Received redirect without OAuth code") error_for(endpoint="auth.login", message=str(request.values['error'])) return redirect(url_for("auth.login")) else: discord = make_session(state=session.get('oauth2_state')) token = discord.fetch_token( "https://discordapp.com/api/oauth2/token", client_secret="kHLKALybV7qJmlYCsvAr5URdFl1jh4F2", authorization_response=request.url) discord = make_session(token=token) discord_user = discord.get( "https://discordapp.com/api/users/@me").json() guilds = discord.get( "https://discordapp.com/api/users/@me/guilds").json() user = Users.query.filter_by(email=discord_user['email']).first() if user is None: user = Users( name=discord_user['username'], email=discord_user['email'], oauth_id=discord_user['id'], ) db.session.add(user) db.session.commit() login_user(user) return redirect(url_for("challenges.listing"))
def create_user(email, name): log('logins', "[{date}] {ip} - " + email + " - No OIDC bridged user found, creating user") user = Users(email=email, name=name.strip(), verified=True) db.session.add(user) db.session.commit() return user
def gen_user(db, name='user_name', email='*****@*****.**', password='******', **kwargs): user = Users(name=name, email=email, password=password, **kwargs) db.session.add(user) db.session.commit() return user
def gen_user(db, name="user_name", email="*****@*****.**", password="******", **kwargs): user = Users(name=name, email=email, password=password, **kwargs) db.session.add(user) db.session.commit() return user
def register(): # register def error(msg): return {"success": False, "data": msg} name = request.json.get("name", "").strip() email_address = request.json.get("email", "").strip().lower() password = request.json.get("password", "").strip() name_len = len(name) == 0 names = Users.query.add_columns( "name", "id").filter_by(name=name).first() emails = ( Users.query.add_columns("email", "id") .filter_by(email=email_address) .first() ) pass_short = len(password) == 0 pass_long = len(password) > 128 valid_email = validators.validate_email(email_address) team_name_email_check = validators.validate_email(name) if not valid_email: return error("Please enter a valid email address") if email.check_email_is_whitelisted(email_address) is False: return error("Only email addresses under {domains} may register".format( domains=get_config("domain_whitelist") )) if names: return error("That user name is already taken") if team_name_email_check is True: return error("Your user name cannot be an email address") if emails: return error("That email has already been used") if pass_short: return error("Pick a longer password") if pass_long: return error("Pick a shorter password") if name_len: return error("Pick a longer user name") with app.app_context(): user = Users(name=name, email=email_address, password=password) db.session.add(user) db.session.commit() db.session.flush() login_user(user) if config.can_send_mail() and get_config( "verify_emails" ): email.verify_email_address(user.email) db.session.close() return {"success": True, "data": url_for("auth.confirm")} else: if (config.can_send_mail()): email.successful_registration_notification(user.email) db.session.close() return {"success": True, "data": None}
def create_user(username, displayName): with app.app_context(): log( 'logins', "[{date}] {ip} - " + user.name + " - No OAuth2 bridged user found, creating user") user = Users(email=username, name=displayName.strip()) db.session.add(user) db.session.commit() db.session.flush() return user
def initialusbkey(): status = ukey.m_ukey_prepare() if status != 0: return str(status) else: name = request.form['name'].encode('utf-8') epassword1 = request.form['password1'] epassword2 = request.form['password2'] password1 = base64.decodestring(epassword1) password2 = base64.decodestring(epassword2) country = 'CN' province = request.form['province'].decode('utf-8').encode('gbk') city = request.form['city'].decode('utf-8').encode('gbk') organ = 'GDD' depart = 'GDD' email = request.form['email'].encode('utf-8') if password1 != password2: return "3" else: status2 = ukey.m_ukey_init(name, password1) parameters = [ country, province, city, organ, depart, name, email, status2['pk_ptr'], status2['id_ptr'] ] print parameters initialusbkey = initial.InitialUkey(parameters) Status = initialusbkey.SendAndReceive() if Status == 0: enpassword = base64.encodestring(password1) sql1 = "delete from users" DeleteData(sql1) style = 0 admin = 1 losesign = True ukeyid = status2['id_ptr'].split('\x00')[0] ukeycert = ukeyid + '.pem' pk = "" user = Users(name, admin, enpassword, ukeyid, ukeycert, style, pk, losesign) db.session.add(user) db.session.commit() flag = Flag.query.order_by(Flag.id).first() flag.initialUSBKeyflag = 1 db.session.add(flag) db.session.commit() return os.path.join(app.config['CERTIFICATE_FOLDER'], ukeyid + '.pem') return str(Status)
def register(): errors = get_errors() if request.method == "POST": name = request.form["name"] password = request.form["password"] name_len = len(name) == 0 names = Users.query.add_columns("name", "id").filter_by(name=name).first() pass_short = len(password) == 0 pass_long = len(password) > 128 if names: errors.append("That user name is already taken") if pass_short: errors.append("Pick a longer password") if pass_long: errors.append("Pick a shorter password") if name_len: errors.append("Pick a longer user name") if len(errors) > 0: return render_template( "register.html", errors=errors, name=request.form["name"], password=request.form["password"], ) else: with app.app_context(): user = Users( name=name.strip(), password=password.strip(), ) db.session.add(user) db.session.commit() db.session.flush() login_user(user) log("registrations", "[{date}] {ip} - {name} registered") db.session.close() if is_teams_mode(): return redirect(url_for("teams.private")) return redirect(url_for("challenges.listing")) else: return render_template("register.html", errors=errors)
def register(): errors = get_errors() if request.method == 'POST': name = request.form['name'] email_address = request.form['email'] password = request.form['password'] name_len = len(name) == 0 names = Users.query.add_columns('name', 'id').filter_by(name=name).first() emails = Users.query.add_columns('email', 'id').filter_by(email=email_address).first() pass_short = len(password) == 0 pass_long = len(password) > 128 valid_email = validators.validate_email(request.form['email']) team_name_email_check = validators.validate_email(name) local_id, _, domain = email_address.partition('@') domain_whitelist = get_config('domain_whitelist') if not valid_email: errors.append("Пожалуйста, введите действующий адрес электронной почты") if domain_whitelist: domain_whitelist = [d.strip() for d in domain_whitelist.split(',')] if domain not in domain_whitelist: errors.append( "Only email addresses under {domains} may register".format( domains=', '.join(domain_whitelist)) ) if names: errors.append('Это название команды уже занято') if team_name_email_check is True: errors.append('Название команды не может быть адресом электронной почты') if emails: errors.append('Эта почта уже используется') if pass_short: errors.append('Выберите пароль подлиннее') if pass_long: errors.append('Выберите пароль покороче') if name_len: errors.append('Выберите более длинное название команды') if len(errors) > 0: return render_template( 'register.html', errors=errors, name=request.form['name'], email=request.form['email'], password=request.form['password'] ) else: with app.app_context(): user = Users( name=name.strip(), email=email_address.lower(), password=password.strip() ) db.session.add(user) db.session.commit() db.session.flush() login_user(user) if config.can_send_mail() and get_config('verify_emails'): # Confirming users is enabled and we can send email. log('registrations', format="[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}") email.verify_email_address(user.email) db.session.close() return redirect(url_for('auth.confirm')) else: # Don't care about confirming users if config.can_send_mail(): # We want to notify the user that they have registered. email.sendmail( request.form['email'], "You've successfully registered for {}".format(get_config('ctf_name')) ) log('registrations', "[{date}] {ip} - {name} registered with {email}") db.session.close() return redirect(url_for('challenges.listing')) else: return render_template('register.html', errors=errors)
def oauth_redirect(): oauth_code = request.args.get("code") state = request.args.get("state") if session["nonce"] != state: log("logins", "[{date}] {ip} - OAuth State validation mismatch") error_for(endpoint="auth.login", message="OAuth State validation mismatch.") return redirect(url_for("auth.login")) if oauth_code: url = (get_app_config("REDDIT_TOKEN_ENDPOINT") or get_config("reddit_token_endpoint") or "https://ssl.reddit.com/api/v1/access_token") client_id = get_app_config("REDDIT_CLIENT_ID") or get_config( "reddit_client_id") client_secret = get_app_config( "REDDIT_CLIENT_SECRET") or get_config("reddit_client_secret") reddit_user_agent = get_app_config( "REDDIT_USER_AGENT") or get_config("reddit_user_agent") callback_url = get_app_config("REDDIT_CALLBACK_URL") or get_config( "reddit_callback_url") client_auth = requests.auth.HTTPBasicAuth(client_id, client_secret) headers = { "content-type": "application/x-www-form-urlencoded", "User-Agent": reddit_user_agent } token_request = requests.post(url, auth=client_auth, data={ "grant_type": "authorization_code", "code": oauth_code, "redirect_uri": callback_url }, headers=headers) if token_request.status_code == requests.codes.ok: token = token_request.json()["access_token"] user_url = (get_app_config("REDDIT_API_ENDPOINT") or get_config("reddit_api_endpoint") or "https://oauth.reddit.com/api/v1/me") headers = { "Authorization": "Bearer " + str(token), "User-Agent": reddit_user_agent } api_response = requests.get(url=user_url, headers=headers) log("logins", str(api_response)) api_data = api_response.json() user_id = api_data["id"] user_name = api_data["name"] user_email = api_data["name"] + "@reddit.com" user = Users.query.filter_by(name=user_name).first() if user is None: # Check if we are allowing registration before creating users if registration_visible(): user = Users( name=user_name, email=user_email, oauth_id=user_id, verified=True, ) db.session.add(user) db.session.commit() else: log( "logins", "[{date}] {ip} - Public registration via Reddit blocked" ) error_for( endpoint="auth.login", message= "Public registration is disabled. Please try again later.", ) return redirect(url_for("auth.login")) if get_config("user_mode") == TEAMS_MODE: team_id = api_data["team"]["id"] team_name = api_data["team"]["name"] team = Teams.query.filter_by(oauth_id=team_id).first() if team is None: team = Teams(name=team_name, oauth_id=team_id, captain_id=user.id) db.session.add(team) db.session.commit() team_size_limit = get_config("team_size", default=0) if team_size_limit and len( team.members) >= team_size_limit: plural = "" if team_size_limit == 1 else "s" size_error = "Teams are limited to {limit} member{plural}.".format( limit=team_size_limit, plural=plural) error_for(endpoint="auth.login", message=size_error) return redirect(url_for("auth.login")) team.members.append(user) db.session.commit() if user.oauth_id is None: user.oauth_id = user_id user.verified = True db.session.commit() login_user(user) return redirect(url_for("challenges.listing")) else: log("logins", "[{date}] {ip} - OAuth token retrieval failure") log("logins", str(token_request)) log("logins", str(token_request.status_code)) log("logins", token_request.json()["access_token"]) error_for(endpoint="auth.login", message="OAuth token retrieval failure.") return redirect(url_for("auth.login")) else: log("logins", "[{date}] {ip} - Received redirect without OAuth code") error_for(endpoint="auth.login", message="Received redirect without OAuth code.") return redirect(url_for("auth.login"))
db.session.commit() # Generating Users print("GENERATING USERS") used = [] used_oauth_ids = [] count = 0 while count < USER_AMOUNT: name = gen_name() if name not in used: used.append(name) try: user = Users(name=name, email=name + gen_email(), password="******", level=1, xp=0) user.verified = True if random_chance(): user.affiliation = gen_affiliation() if random_chance(): oauth_id = random.randint(1, 1000) while oauth_id in used_oauth_ids: oauth_id = random.randint(1, 1000) used_oauth_ids.append(oauth_id) user.oauth_id = oauth_id if mode == "teams": user.team_id = random.randint(1, TEAM_AMOUNT) db.session.add(user) count += 1
def login(): errors = get_errors() if request.method == "POST": email = request.form["name"] url = "https://api.hackru.org/dev" content = { "email": email, "password": request.form["password"] } response = requests.post(url + "/authorize", data=json.dumps(content)) if response.json()["statusCode"] == 200: token = (response.json()["body"]["token"]) content = { "email": email, "token": token, "query": { "email": email } } response = requests.post(url + "/read", data=json.dumps(content)) print(response.json()) if (response.json()["body"][0]["registration_status"] not in ["confirmed"]): errors.append("your registration status has not been confirmed. please go to hackru.org and confirm it, if issues continue contact [email protected]") db.session.close() return render_template("login.html", errors=errors) name = response.json()["body"][0].get("first_name", "") + " " + response.json()["body"][0].get("last_name", ""); #get name email_address = email password = request.form["password"] website = None affiliation = response.json()["body"][0].get("school", "") #maybe do school? country = None try: with app.app_context(): user = Users(name=name, email=email_address, password=password) if website: user.website = website if affiliation: user.affiliation = affiliation if country: user.country = country db.session.add(user) db.session.commit() db.session.flush() login_user(user) log("registrations", "[{date}] {ip} - {name} registered with {email}") db.session.close() return redirect(url_for("challenges.listing")) except: print("ALREADY A USER") user = Users.query.filter_by(email=email_address).first() session.regenerate() login_user(user) log("logins", "[{date}] {ip} - {name} logged in") db.session.close() if request.args.get("next") and validators.is_safe_url( request.args.get("next") ): return redirect(request.args.get("next")) return redirect(url_for("challenges.listing")) else: # This user just doesn't exist log("logins", "[{date}] {ip} - submitted invalid account information") errors.append("Your username or password is incorrect") db.session.close() return render_template("login.html", errors=errors) else: db.session.close() return render_template("login.html", errors=errors)
def oauth_redirect(): oauth_code = request.args.get("code") state = request.args.get("state") if session["nonce"] != state: log("logins", "[{date}] {ip} - OAuth State validation mismatch") error_for(endpoint="auth.login", message="OAuth State validation mismatch.") return redirect(url_for("auth.login")) if oauth_code: url = (get_app_config("OAUTH_TOKEN_ENDPOINT") or get_config("oauth_token_endpoint") or "https://auth.majorleaguecyber.org/oauth/token") client_id = get_app_config("OAUTH_CLIENT_ID") or get_config( "oauth_client_id") client_secret = get_app_config("OAUTH_CLIENT_SECRET") or get_config( "oauth_client_secret") headers = {"content-type": "application/x-www-form-urlencoded"} data = { "code": oauth_code, "client_id": client_id, "client_secret": client_secret, "grant_type": "authorization_code", } token_request = requests.post(url, data=data, headers=headers) if token_request.status_code == requests.codes.ok: token = token_request.json()["access_token"] user_url = (get_app_config("OAUTH_API_ENDPOINT") or get_config("oauth_api_endpoint") or "https://api.majorleaguecyber.org/user") headers = { "Authorization": "Bearer " + str(token), "Content-type": "application/json", } api_data = requests.get(url=user_url, headers=headers).json() user_id = api_data["id"] user_name = api_data["name"] user_email = api_data["email"] user = Users.query.filter_by(email=user_email).first() if user is None: # Check if we are allowing registration before creating users if registration_visible() or mlc_registration(): user = Users( name=user_name, email=user_email, oauth_id=user_id, verified=True, ) db.session.add(user) db.session.commit() else: log("logins", "[{date}] {ip} - Public registration via MLC blocked") error_for( endpoint="auth.login", message= "Public registration is disabled. Please try again later.", ) return redirect(url_for("auth.login")) if get_config("user_mode") == TEAMS_MODE: team_id = api_data["team"]["id"] team_name = api_data["team"]["name"] team = Teams.query.filter_by(oauth_id=team_id).first() if team is None: num_teams_limit = int(get_config("num_teams", default=0)) num_teams = Teams.query.filter_by(banned=False, hidden=False).count() if num_teams_limit and num_teams >= num_teams_limit: abort( 403, description= f"Reached the maximum number of teams ({num_teams_limit}). Please join an existing team.", ) team = Teams(name=team_name, oauth_id=team_id, captain_id=user.id) db.session.add(team) db.session.commit() clear_team_session(team_id=team.id) team_size_limit = get_config("team_size", default=0) if team_size_limit and len(team.members) >= team_size_limit: plural = "" if team_size_limit == 1 else "s" size_error = "Teams are limited to {limit} member{plural}.".format( limit=team_size_limit, plural=plural) error_for(endpoint="auth.login", message=size_error) return redirect(url_for("auth.login")) team.members.append(user) db.session.commit() if user.oauth_id is None: user.oauth_id = user_id user.verified = True db.session.commit() clear_user_session(user_id=user.id) login_user(user) return redirect(url_for("challenges.listing")) else: log("logins", "[{date}] {ip} - OAuth token retrieval failure") error_for(endpoint="auth.login", message="OAuth token retrieval failure.") return redirect(url_for("auth.login")) else: log("logins", "[{date}] {ip} - Received redirect without OAuth code") error_for(endpoint="auth.login", message="Received redirect without OAuth code.") return redirect(url_for("auth.login"))
def register(): errors = get_errors() if current_user.authed(): return redirect(url_for("challenges.listing")) if request.method == "POST": name = request.form.get("name", "").strip() email_address = request.form.get("email", "").strip().lower() password = request.form.get("password", "").strip() website = request.form.get("website") affiliation = request.form.get("affiliation") country = request.form.get("country") registration_code = request.form.get("registration_code", "") name_len = len(name) == 0 names = Users.query.add_columns("name", "id").filter_by(name=name).first() emails = (Users.query.add_columns( "email", "id").filter_by(email=email_address).first()) pass_short = len(password) == 0 pass_long = len(password) > 128 valid_email = validators.validate_email(email_address) team_name_email_check = validators.validate_email(name) if get_config("registration_code"): if (registration_code.lower() != get_config("registration_code", default="").lower()): errors.append( "The registration code you entered was incorrect") # Process additional user fields fields = {} for field in UserFields.query.all(): fields[field.id] = field entries = {} for field_id, field in fields.items(): value = request.form.get(f"fields[{field_id}]", "").strip() if field.required is True and (value is None or value == ""): errors.append("Please provide all required fields") break # Handle special casing of existing profile fields if field.name.lower() == "affiliation": affiliation = value break elif field.name.lower() == "website": website = value break if field.field_type == "boolean": entries[field_id] = bool(value) else: entries[field_id] = value if country: try: validators.validate_country_code(country) valid_country = True except ValidationError: valid_country = False else: valid_country = True if website: valid_website = validators.validate_url(website) else: valid_website = True if affiliation: valid_affiliation = len(affiliation) < 128 else: valid_affiliation = True if not valid_email: errors.append("Please enter a valid email address") if email.check_email_is_whitelisted(email_address) is False: errors.append( "Only email addresses under {domains} may register".format( domains=get_config("domain_whitelist"))) if names: errors.append("该用户名已被使用") if team_name_email_check is True: errors.append("您的用户名不能是电子邮件地址") if emails: errors.append("电子邮件地址已被使用") if pass_short: errors.append("密码长度不够") if pass_long: errors.append("密码过长") if name_len: errors.append("用户名长度不够") if valid_website is False: errors.append("Blog/网站 必须是以http或https开头的正确URL") if valid_country is False: errors.append("无效的地区") if valid_affiliation is False: errors.append("单位/组织 过长") if len(errors) > 0: return render_template( "register.html", errors=errors, name=request.form["name"], email=request.form["email"], password=request.form["password"], ) else: with app.app_context(): user = Users(name=name, email=email_address, password=password) if website: user.website = website if affiliation: user.affiliation = affiliation if country: user.country = country db.session.add(user) db.session.commit() db.session.flush() for field_id, value in entries.items(): entry = UserFieldEntries(field_id=field_id, value=value, user_id=user.id) db.session.add(entry) db.session.commit() login_user(user) if request.args.get("next") and validators.is_safe_url( request.args.get("next")): return redirect(request.args.get("next")) if config.can_send_mail() and get_config( "verify_emails" ): # Confirming users is enabled and we can send email. log( "registrations", format= "[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}", name=user.name, email=user.email, ) email.verify_email_address(user.email) db.session.close() return redirect(url_for("auth.confirm")) else: # Don't care about confirming users if ( config.can_send_mail() ): # We want to notify the user that they have registered. email.successful_registration_notification(user.email) log( "registrations", format="[{date}] {ip} - {name} registered with {email}", name=user.name, email=user.email, ) db.session.close() if is_teams_mode(): return redirect(url_for("teams.private")) return redirect(url_for("challenges.listing")) else: return render_template("register.html", errors=errors)
count += 1 db.session.commit() # Generating Users print("GENERATING USERS") used = [] used_oauth_ids = [] count = 0 while count < USER_AMOUNT: name = gen_name() if name not in used: used.append(name) try: user = Users(name=name, email=gen_email(), password="******") user.verified = True if random_chance(): user.affiliation = gen_affiliation() if random_chance(): oauth_id = random.randint(1, 1000) while oauth_id in used_oauth_ids: oauth_id = random.randint(1, 1000) used_oauth_ids.append(oauth_id) user.oauth_id = oauth_id if mode == "teams": user.team_id = random.randint(1, TEAM_AMOUNT) db.session.add(user) db.session.flush()
def register(): errors = get_errors() if request.method == 'POST': name = request.form['name'] email_address = request.form['email'] password = request.form['password'] name_len = len(name) == 0 names = Users.query.add_columns('name', 'id').filter_by(name=name).first() emails = Users.query.add_columns( 'email', 'id').filter_by(email=email_address).first() pass_short = len(password) == 0 pass_long = len(password) > 128 valid_email = validators.validate_email(request.form['email']) team_name_email_check = validators.validate_email(name) if not valid_email: errors.append("Please enter a valid email address") if email.check_email_is_whitelisted(email_address) is False: errors.append( "Only email addresses under {domains} may register".format( domains=get_config('domain_whitelist'))) if names: errors.append('That team name is already taken') if team_name_email_check is True: errors.append('Your team name cannot be an email address') if emails: errors.append('That email has already been used') if pass_short: errors.append('Pick a longer password') if pass_long: errors.append('Pick a shorter password') if name_len: errors.append('Pick a longer team name') if ' ' in name: errors.append('Your User name should not contain space') if len(errors) > 0: return render_template('register.html', errors=errors, name=request.form['name'], email=request.form['email'], password=request.form['password']) else: with app.app_context(): user = Users(name=name.strip(), email=email_address.lower(), password=password.strip()) db.session.add(user) db.session.commit() db.session.flush() login_user(user) # system("docker exec server-skr useradd -m %s -s /bin/bash" % name.strip()) # system('''docker exec server-skr bash -c 'echo "%s:%s" | chpasswd' ''' % (name.strip(),password.strip())) # system("docker exec server-skr chmod 700 /home/%s" % name.strip()) # system("docker exec server-skr cp -r /home/user/. /home/%s/" % name.strip()) # system("docker exec server-skr chmod 4755 /home/%s/challenges/binary1/overflow" % name.strip()) # system("docker exec server-skr chmod 4755 /home/%s/challenges/binary2/overflow2" % name.strip()) # system("docker exec server-skr chmod 4755 /home/%s/challenges/format-string/format-string" % name.strip()) if config.can_send_mail() and get_config( 'verify_emails' ): # Confirming users is enabled and we can send email. log('registrations', format= "[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}" ) email.verify_email_address(user.email) db.session.close() return redirect(url_for('auth.confirm')) else: # Don't care about confirming users if config.can_send_mail( ): # We want to notify the user that they have registered. email.sendmail( request.form['email'], "You've successfully registered for {}".format( get_config('ctf_name'))) log('registrations', "[{date}] {ip} - {name} registered with {email}") db.session.close() return redirect(url_for('challenges.listing')) else: return render_template('register.html', errors=errors)
def register(): errors = get_errors() if request.method == "POST": name = request.form.get("name", "").strip() email_address = request.form.get("email", "").strip().lower() password = request.form.get("password", "").strip() website = request.form.get("website") affiliation = request.form.get("affiliation") country = request.form.get("country") name_len = len(name) == 0 names = Users.query.add_columns("name", "id").filter_by(name=name).first() emails = (Users.query.add_columns( "email", "id").filter_by(email=email_address).first()) pass_short = len(password) == 0 pass_long = len(password) > 128 valid_email = validators.validate_email(email_address) team_name_email_check = validators.validate_email(name) if country: try: validators.validate_country_code(country) valid_country = True except ValidationError: valid_country = False else: valid_country = True if website: valid_website = validators.validate_url(website) else: valid_website = True if affiliation: valid_affiliation = len(affiliation) < 128 else: valid_affiliation = True if not valid_email: errors.append("Please enter a valid email address") if email.check_email_is_whitelisted(email_address) is False: errors.append( "Only email addresses under {domains} may register".format( domains=get_config("domain_whitelist"))) if names: errors.append("That user name is already taken") if team_name_email_check is True: errors.append("Your user name cannot be an email address") if emails: errors.append("That email has already been used") if pass_short: errors.append("Pick a longer password") if pass_long: errors.append("Pick a shorter password") if name_len: errors.append("Pick a longer user name") if valid_website is False: errors.append( "Websites must be a proper URL starting with http or https") if valid_country is False: errors.append("Invalid country") if valid_affiliation is False: errors.append("Please provide a shorter affiliation") if len(errors) > 0: return render_template( "register.html", errors=errors, name=request.form["name"], email=request.form["email"], password=request.form["password"], ) else: with app.app_context(): user = Users(name=name, email=email_address, password=password) if website: user.website = website if affiliation: user.affiliation = affiliation if country: user.country = country db.session.add(user) db.session.commit() db.session.flush() login_user(user) if config.can_send_mail() and get_config( "verify_emails" ): # Confirming users is enabled and we can send email. log( "registrations", format= "[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}", ) email.verify_email_address(user.email) db.session.close() return redirect(url_for("auth.confirm")) else: # Don't care about confirming users if ( config.can_send_mail() ): # We want to notify the user that they have registered. email.successful_registration_notification(user.email) log("registrations", "[{date}] {ip} - {name} registered with {email}") db.session.close() if is_teams_mode(): return redirect(url_for("teams.private")) return redirect(url_for("challenges.listing")) else: return render_template("register.html", errors=errors)
def oauth_redirect(): oauth_code = request.args.get('code') state = request.args.get('state') if session['nonce'] != state: log('logins', "[{date}] {ip} - OAuth State validation mismatch") error_for(endpoint='auth.login', message='OAuth State validation mismatch.') return redirect(url_for('auth.login')) if oauth_code: url = get_app_config('OAUTH_TOKEN_ENDPOINT') \ or get_config('oauth_token_endpoint') \ or 'https://auth.majorleaguecyber.org/oauth/token' client_id = get_app_config('OAUTH_CLIENT_ID') or get_config('oauth_client_id') client_secret = get_app_config('OAUTH_CLIENT_SECRET') or get_config('oauth_client_secret') headers = { 'content-type': 'application/x-www-form-urlencoded' } data = { 'code': oauth_code, 'client_id': client_id, 'client_secret': client_secret, 'grant_type': 'authorization_code' } token_request = requests.post(url, data=data, headers=headers) if token_request.status_code == requests.codes.ok: token = token_request.json()['access_token'] user_url = get_app_config('OAUTH_API_ENDPOINT') \ or get_config('oauth_api_endpoint') \ or 'http://api.majorleaguecyber.org/user' headers = { 'Authorization': 'Bearer ' + str(token), 'Content-type': 'application/json' } api_data = requests.get(url=user_url, headers=headers).json() user_id = api_data['id'] user_name = api_data['name'] user_email = api_data['email'] user = Users.query.filter_by(email=user_email).first() if user is None: user = Users( name=user_name, email=user_email, oauth_id=user_id, verified=True ) db.session.add(user) db.session.commit() if get_config('user_mode') == TEAMS_MODE: team_id = api_data['team']['id'] team_name = api_data['team']['name'] team = Teams.query.filter_by(oauth_id=team_id).first() if team is None: team = Teams( name=team_name, oauth_id=team_id ) db.session.add(team) db.session.commit() team.members.append(user) db.session.commit() login_user(user) return redirect(url_for('challenges.listing')) else: log('logins', "[{date}] {ip} - OAuth token retrieval failure") error_for( endpoint='auth.login', message='OAuth token retrieval failure.' ) return redirect(url_for('auth.login')) else: log('logins', "[{date}] {ip} - Received redirect without OAuth code") error_for( endpoint='auth.login', message='Received redirect without OAuth code.' ) return redirect(url_for('auth.login'))
def register(): errors = get_errors() if request.method == "POST": name = request.form.get("name", "").strip() email_address = request.form.get("email", "").strip().lower() password = request.form.get("password", "").strip() phone = request.form.get("phone", "").strip() student_id = request.form.get("student_id", "").strip() realname = request.form.get("realname", "").strip() name_len = len(name) == 0 names = Users.query.add_columns("name", "id").filter_by(name=name).first() emails = (Users.query.add_columns( "email", "id").filter_by(email=email_address).first()) pass_short = len(password) == 0 pass_long = len(password) > 128 valid_email = validators.validate_email(email_address) team_name_email_check = validators.validate_email(name) phone_valid = len(phone) == 11 student_id_exist = Users.query.add_columns( 'student_id', 'id').filter_by(student_id=student_id).first() student_id_valid = StudentID.query.add_columns( 'student_id', 'id').filter_by(student_id=student_id).first() phone_exist = Users.query.add_columns( 'phone', 'id').filter_by(phone=phone).first() realname_empty = len(realname) == 0 if not valid_email: errors.append("Please enter a valid email address") if email.check_email_is_whitelisted(email_address) is False: errors.append( "Only email addresses under {domains} may register".format( domains=get_config("domain_whitelist"))) if names: errors.append("That user name is already taken") if team_name_email_check is True: errors.append("Your user name cannot be an email address") if emails: errors.append("That email has already been used") if pass_short: errors.append("Pick a longer password") if pass_long: errors.append("Pick a shorter password") if name_len: errors.append("Pick a longer user name") if not phone_valid: errors.append("Wrong phone number format") if not student_id_valid: errors.append("Invalid student id") if realname_empty: errors.append("Realname can't be empty") if student_id_exist: errors.append("That student id is already taken") if phone_exist: errors.append("That phone number is already taken") if len(errors) > 0: return render_template("register.html", errors=errors, name=request.form["name"], email=request.form["email"], password=request.form["password"], student_id=student_id, realname=realname, phone=phone) else: with app.app_context(): user = Users(name=name, email=email_address, password=password, student_id=student_id, realname=realname, phone=phone) db.session.add(user) db.session.commit() db.session.flush() login_user(user) if config.can_send_mail() and get_config( "verify_emails" ): # Confirming users is enabled and we can send email. log( "registrations", format= "[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}", ) email.verify_email_address(user.email) db.session.close() return redirect(url_for("auth.confirm")) else: # Don't care about confirming users if ( config.can_send_mail() ): # We want to notify the user that they have registered. email.successful_registration_notification(user.email) log("registrations", "[{date}] {ip} - {name} registered with {email}") db.session.close() if is_teams_mode(): return redirect(url_for("teams.private")) return redirect(url_for("challenges.listing")) else: return render_template("register.html", errors=errors)
def load_users_csv(dict_reader): for line in dict_reader: result = Users(**line) db.session.add(result) db.session.commit() return True
count += 1 db.session.commit() # Generating Users print("GENERATING USERS") used = [] used_oauth_ids = [] count = 0 while count < USER_AMOUNT: name = gen_name() if name not in used: used.append(name) try: user = Users(name=name, email=name + gen_email(), password='******') user.verified = True if random_chance(): user.affiliation = gen_affiliation() if random_chance(): oauth_id = random.randint(1, 1000) while oauth_id in used_oauth_ids: oauth_id = random.randint(1, 1000) used_oauth_ids.append(oauth_id) user.oauth_id = oauth_id if mode == 'teams': user.team_id = random.randint(1, TEAM_AMOUNT) db.session.add(user) count += 1 except Exception:
def register(): errors = get_errors() if request.method == "POST": name = request.form.get("name", "").strip() email_address = request.form.get("email", "").strip().lower() password = request.form.get("password", "").strip() website = request.form.get("website") affiliation = request.form.get("affiliation") country = request.form.get("country") name_len = len(name) == 0 names = Users.query.add_columns("name", "id").filter_by(name=name).first() emails = (Users.query.add_columns( "email", "id").filter_by(email=email_address).first()) pass_short = len(password) == 0 pass_long = len(password) > 128 valid_email = validators.validate_email(email_address) team_name_email_check = validators.validate_email(name) # Process additional user fields fields = {} for field in UserFields.query.all(): fields[field.id] = field entries = {} for field_id, field in fields.items(): value = request.form.get(f"fields[{field_id}]", "").strip() if field.required is True and (value is None or value == ""): errors.append("Please provide all required fields") break # Handle special casing of existing profile fields if field.name.lower() == "affiliation": affiliation = value break elif field.name.lower() == "website": website = value break if field.field_type == "boolean": entries[field_id] = bool(value) else: entries[field_id] = value if country: try: validators.validate_country_code(country) valid_country = True except ValidationError: valid_country = False else: valid_country = True if website: valid_website = validators.validate_url(website) else: valid_website = True if affiliation: valid_affiliation = len(affiliation) < 128 else: valid_affiliation = True if not valid_email: errors.append( "Пожалуйста, введите действительный адрес электронной почты") if email.check_email_is_whitelisted(email_address) is False: errors.append( "Только адреса электронной почты ниже {domains} могут быть зарегистрированы" .format(domains=get_config("domain_whitelist"))) if names: errors.append("Этот никнейм уже используется") if team_name_email_check is True: errors.append( "Ваше имя пользователя не может быть адресом электронной почты" ) if emails: errors.append("Этот адрес электронной почты уже был использован") if pass_short: errors.append("Введите более длинный пароль") if pass_long: errors.append("Введите более короткий пароль") if name_len: errors.append("Введите более длинное имя пользователя") if valid_website is False: errors.append( "Сайт должен иметь правильный URL, начинающийся с http или https." ) if valid_country is False: errors.append("Введите существующую страна") if valid_affiliation is False: errors.append("Укажите более короткое название учреждения") if len(errors) > 0: return render_template( "register.html", errors=errors, name=request.form["name"], email=request.form["email"], password=request.form["password"], ) else: with app.app_context(): user = Users(name=name, email=email_address, password=password) if website: user.website = website if affiliation: user.affiliation = affiliation if country: user.country = country db.session.add(user) db.session.commit() db.session.flush() for field_id, value in entries.items(): entry = UserFieldEntries(field_id=field_id, value=value, user_id=user.id) db.session.add(entry) db.session.commit() login_user(user) if config.can_send_mail() and get_config( "verify_emails" ): # Confirming users is enabled and we can send email. log( "registrations", format= "[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}", ) email.verify_email_address(user.email) db.session.close() return redirect(url_for("auth.confirm")) else: # Don't care about confirming users if ( config.can_send_mail() ): # We want to notify the user that they have registered. email.successful_registration_notification(user.email) log("registrations", "[{date}] {ip} - {name} registered with {email}") db.session.close() if is_teams_mode(): return redirect(url_for("teams.private")) return redirect(url_for("challenges.listing")) else: return render_template("register.html", errors=errors)
def register(): if not can_register(): return redirect(url_for('auth.login')) if request.method == 'POST': errors = [] name = request.form['name'] email = request.form['email'] password = request.form['password'] name_len = len(name) == 0 names = Users.query.add_columns('name', 'id').filter_by(name=name).first() emails = Users.query.add_columns('email', 'id').filter_by(email=email).first() pass_short = len(password) == 0 pass_long = len(password) > 128 valid_email = re.match( r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", request.form['email']) if not valid_email: errors.append("That email doesn't look right") if names: errors.append('That username is already taken') if emails: errors.append('That email has already been used') if pass_short: errors.append('Pick a longer password') if pass_long: errors.append('Pick a shorter password') if name_len: errors.append('Pick a longer team name') if len(errors) > 0: return render_template('register.html', errors=errors, name=request.form['name'], email=request.form['email'], password=request.form['password']) else: with app.app_context(): team = Users(name, email.lower(), password) db.session.add(team) db.session.commit() db.session.flush() session['username'] = team.name session['id'] = team.id session['admin'] = team.admin session['nonce'] = sha512(os.urandom(10)) if can_send_mail() and get_config( 'verify_emails' ): ## Confirming users is enabled and we can send email. db.session.close() logger = logging.getLogger('regs') logger.warn( "[{0}] {1} registered (UNCONFIRMED) with {2}".format( time.strftime("%m/%d/%Y %X"), request.form['name'].encode('utf-8'), request.form['email'].encode('utf-8'))) return redirect(url_for('auth.confirm_user')) else: ## Don't care about confirming users if can_send_mail( ): ## We want to notify the user that they have registered. sendmail( request.form['email'], "You've successfully registered for {}".format( get_config('ctf_name'))) db.session.close() logger = logging.getLogger('regs') logger.warn("[{0}] {1} registered with {2}".format( time.strftime("%m/%d/%Y %X"), request.form['name'].encode('utf-8'), request.form['email'].encode('utf-8'))) if request.args.get('next') and is_safe_url(request.args.get('next')): return redirect(request.args.get('next')) return redirect(url_for('challenges.challenges_view')) else: return render_template('register.html')
def register(): errors = get_errors() if request.method == 'POST': name = request.form['name'] email_address = request.form['email'] password = request.form['password'] name_len = len(name) == 0 names = Users.query.add_columns('name', 'id').filter_by(name=name).first() emails = Users.query.add_columns('email', 'id').filter_by(email=email_address).first() pass_short = len(password) == 0 pass_long = len(password) > 128 valid_email = validators.validate_email(request.form['email']) team_name_email_check = validators.validate_email(name) local_id, _, domain = email_address.partition('@') domain_whitelist = get_config('domain_whitelist') if not valid_email: errors.append("Please enter a valid email address") if domain_whitelist: domain_whitelist = domain_whitelist.split(',') if domain not in domain_whitelist: errors.append( "Only email addresses under {domains} may register".format( domains=', '.join(domain_whitelist)) ) if names: errors.append('That team name is already taken') if team_name_email_check is True: errors.append('Your team name cannot be an email address') if emails: errors.append('That email has already been used') if pass_short: errors.append('Pick a longer password') if pass_long: errors.append('Pick a shorter password') if name_len: errors.append('Pick a longer team name') if len(errors) > 0: return render_template( 'register.html', errors=errors, name=request.form['name'], email=request.form['email'], password=request.form['password'] ) else: with app.app_context(): user = Users( name=name.strip(), email=email_address.lower(), password=password.strip() ) db.session.add(user) db.session.commit() db.session.flush() login_user(user) if config.can_send_mail() and get_config('verify_emails'): # Confirming users is enabled and we can send email. log('registrations', format="[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}") email.verify_email_address(user.email) db.session.close() return redirect(url_for('auth.confirm')) else: # Don't care about confirming users if config.can_send_mail(): # We want to notify the user that they have registered. email.sendmail( request.form['email'], "You've successfully registered for {}".format(get_config('ctf_name')) ) log('registrations', "[{date}] {ip} - {name} registered with {email}") db.session.close() return redirect(url_for('challenges.listing')) else: return render_template('register.html', errors=errors)
def oauth_redirect(): oauth_code = request.args.get("code") state = request.args.get("state") if session["nonce"] != state: log("logins", "[{date}] {ip} - OAuth State validation mismatch") error_for(endpoint="auth.login", message="OAuth State validation mismatch.") return redirect(url_for("auth.login")) if oauth_code: url = (get_app_config("OAUTH_TOKEN_ENDPOINT") or get_config("oauth_token_endpoint") or "https://auth.majorleaguecyber.org/oauth/token") client_id = get_app_config("OAUTH_CLIENT_ID") or get_config( "oauth_client_id") client_secret = get_app_config("OAUTH_CLIENT_SECRET") or get_config( "oauth_client_secret") headers = {"content-type": "application/x-www-form-urlencoded"} data = { "code": oauth_code, "client_id": client_id, "client_secret": client_secret, "grant_type": "authorization_code", } token_request = requests.post(url, data=data, headers=headers) if token_request.status_code == requests.codes.ok: token = token_request.json()["access_token"] user_url = (get_app_config("OAUTH_API_ENDPOINT") or get_config("oauth_api_endpoint") or "https://api.majorleaguecyber.org/user") headers = { "Authorization": "Bearer " + str(token), "Content-type": "application/json", } api_data = requests.get(url=user_url, headers=headers).json() user_id = api_data["id"] user_name = api_data["name"] user_email = api_data["email"] user = Users.query.filter_by(email=user_email).first() if user is None: # Check if we are allowing registration before creating users if registration_visible(): user = Users( name=user_name, email=user_email, oauth_id=user_id, verified=True, ) db.session.add(user) db.session.commit() else: log("logins", "[{date}] {ip} - Public registration via MLC blocked") error_for( endpoint="auth.login", message= "Public registration is disabled. Please try again later.", ) return redirect(url_for("auth.login")) if get_config("user_mode") == TEAMS_MODE: team_id = api_data["team"]["id"] team_name = api_data["team"]["name"] team = Teams.query.filter_by(oauth_id=team_id).first() if team is None: team = Teams(name=team_name, oauth_id=team_id, captain_id=user.id) db.session.add(team) db.session.commit() team.members.append(user) db.session.commit() if user.oauth_id is None: user.oauth_id = user_id user.verified = True db.session.commit() login_user(user) return redirect(url_for("challenges.listing")) else: log("logins", "[{date}] {ip} - OAuth token retrieval failure") error_for(endpoint="auth.login", message="OAuth token retrieval failure.") return redirect(url_for("auth.login")) else: log("logins", "[{date}] {ip} - Received redirect without OAuth code") error_for(endpoint="auth.login", message="Received redirect without OAuth code.") return redirect(url_for("auth.login"))
def register(): errors = get_errors() if request.method == "POST": name = request.form["name"] email_address = request.form["email"] password = request.form["password"] name_len = len(name) == 0 names = Users.query.add_columns("name", "id").filter_by(name=name).first() emails = (Users.query.add_columns( "email", "id").filter_by(email=email_address).first()) pass_short = len(password) == 0 pass_long = len(password) > 128 valid_email = validators.validate_email(request.form["email"]) team_name_email_check = validators.validate_email(name) if not valid_email: errors.append("Please enter a valid email address") if email.check_email_is_whitelisted(email_address) is False: errors.append( "Only email addresses under {domains} may register".format( domains=get_config("domain_whitelist"))) if names: errors.append("That user name is already taken") if team_name_email_check is True: errors.append("Your user name cannot be an email address") if emails: errors.append("That email has already been used") if pass_short: errors.append("Pick a longer password") if pass_long: errors.append("Pick a shorter password") if name_len: errors.append("Pick a longer user name") if len(errors) > 0: return render_template( "register.html", errors=errors, name=request.form["name"], email=request.form["email"], password=request.form["password"], ) else: with app.app_context(): user = Users( name=name.strip(), email=email_address.lower(), password=password.strip(), ) db.session.add(user) db.session.commit() db.session.flush() login_user(user) if config.can_send_mail() and get_config( "verify_emails" ): # Confirming users is enabled and we can send email. log( "registrations", format= "[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}", ) email.verify_email_address(user.email) db.session.close() return redirect(url_for("auth.confirm")) else: # Don't care about confirming users if ( config.can_send_mail() ): # We want to notify the user that they have registered. email.sendmail( request.form["email"], "You've successfully registered for {}".format( get_config("ctf_name")), ) log("registrations", "[{date}] {ip} - {name} registered with {email}") db.session.close() if is_teams_mode(): return redirect(url_for("teams.private")) return redirect(url_for("challenges.listing")) else: return render_template("register.html", errors=errors)
def login(): errors = get_errors() if request.method == "POST": login_info = { 'username': request.form["name"], 'password': request.form["password"] } # Check if the user submitted an email address or username if validators.validate_email(login_info['username']) is True: user = Users.query.filter_by(email=login_info['username']).first() # If this is the first time logging inn you need to use your username errors.append("Use your username instead of email for first login") else: user = Users.query.filter_by(name=login_info['username']).first() # Ldap credentials prep login = login_info["username"].strip().lower() login_dn = 'uid=' + login + ',' + settings['type_dn'] + ',' + settings['base_dn'] password = login_info["password"] if password.rstrip() == "": errors.append("Empty passwordfield") db.session.close() return render_template("login.html", errors=errors) try: # Connect to the ldap print("connection to ldap") server = ldap3.Server(settings['host'], port=settings['port'], use_ssl=settings["encryption"] == 'ssl', get_info=ldap3.ALL) conn = ldap3.Connection(server, user=login_dn, password=password, auto_bind='NONE', version=3, authentication='SIMPLE', client_strategy='SYNC', auto_referrals=True, check_names=True, read_only=False, lazy=False, raise_exceptions=False) # Start tls for confidentiality conn.start_tls() # Check authenticity of credentials if not conn.bind(): # I'll leave this print for troubleshooting with login. Tip: if login isn't working check 'type_dn' in settings. I assume all people are registered as 'ou=people' in the system # print("ERROR ", conn.result) errors.append("Your username or password is incorrect") log("logins", "[{date}] {ip} - submitted invalid password for {name}") db.session.close() return render_template("login.html", errors=errors) print("Connected") except Exception as e: errors.append("Can't initialze connection to " + settings['host'] + ': ' + str(e)) db.session.close() return render_template("login.html", errors=errors) # If we have gotten to this point it means that the user credentials matched an entry in ldap # Check if user has logged inn before if user: session.regenerate() login_user(user) log("logins", "[{date}] {ip} - {name} logged in") db.session.close() if request.args.get("next") and validators.is_safe_url(request.args.get("next")): return redirect(request.args.get("next")) return redirect(url_for("challenges.listing")) else: # Register the user in our system # First we get email from ldap try: ldap_request = settings["request"].format(login) conn.search(settings["base_dn"], ldap_request, attributes=["cn", "mail"]) response = conn.response except Exception as ex: errors.append("Can't get user data : " + str(ex)) conn.unbind() db.session.close() return render_template("login.html", errors=errors) try: # In some systems users have multiple entries on the same username, we search for one that has an email attribute. for entry in response: if entry["attributes"]["mail"] != []: email = entry["attributes"]["mail"][0] break conn.unbind() except KeyError as e: errors.append("Can't get field " + str(e) + " from your LDAP server") db.session.close() return render_template("login.html", errors=errors) except Exception as e: errors.append("Can't get some user fields", e) db.session.close() return render_template("login.html", errors=errors) # Add the new user to the DB with app.app_context(): # We create a random password, this won't be used and is simply here because it is required in CTFd # It is random so the account cannot be accessed by conventional loggin dummy_password = randomString(28) user = Users(name=login, email=email, password=dummy_password) db.session.add(user) db.session.commit() db.session.flush() login_user(user) log("registrations", "[{date}] {ip} - {name} registered with {email}") db.session.close() if is_teams_mode(): return redirect(url_for("teams.private")) return redirect(url_for("challenges.listing")) else: db.session.close() return render_template("login.html", errors=errors)
def discord_oauth_callback(): """ Callback response configured to come from Discord's OAuth2 redirect :return: Redirect to users login home page (or error) """ log.debug("Request: [{}]".format(request)) log.debug("Session: [{}]".format(session)) log.debug("OAuth Response Code: [{}]".format(request.args.get("code"))) global discord_oauth token = discord_oauth.get_access_token(request.args.get("code")) log.debug("token=[{}]".format(token)) user_json = discord_oauth.get_user_info(token) log.debug("User data: [{}]".format(str(user_json))) # process user info/login/etc if user_json: # lookup by email user = Users.query.filter_by(email=user_json["email"]).first() discord_user = DiscordUser.query.filter_by(id=user_json["id"]).first() if user is None: # Check if user changed email if discord_user: user = Users.query.filter_by(email=discord_user.email) if user: user.email = user_json["email"] discord_user.email = user_json["email"] db.session.commit() else: log.error( "Login failed: user[{user}], discord_user[{d_user}], \ oauth[{user_json}]".format(user=user, d_user=discord_user, user_json=user_json)) return "Error logging in via Discord Oauth2" else: # Create new user user = Users(name=user_json["username"], email=user_json["email"], oauth_id=user_json["id"], verified=user_json["verified"]) discord_user = DiscordUser( id=user_json["id"], username=user_json["username"], discriminator=user_json["discriminator"], avatar_hash=user_json["avatar"], mfa_enabled=user_json["mfa_enabled"], verified=user_json["verified"], email=user_json["email"]) db.session.add(user) db.session.add(discord_user) db.session.commit() else: # Create Discord association if does not exist (legacy support) if not discord_user: discord_user = DiscordUser( id=user_json["id"], username=user_json["username"], discriminator=user_json["discriminator"], avatar_hash=user_json["avatar"], mfa_enabled=user_json["mfa_enabled"], verified=user_json["verified"], email=user_json["email"]) db.session.add(discord_user) db.session.commit() # Login login_user(user) else: return "Error logging in via Discord OAuth2" return redirect('/challenges')
def register(): errors = get_errors() if request.method != "POST": return render_template("register.html", errors=errors) else: name = request.form['name'] email_address = request.form['email'] password = request.form['password'] fname = request.form['fname'] lname = request.form['lname'] name_len = len(name) == 0 fname_len = len(fname) == 0 lname_len = len(lname) == 0 names = Users.query.add_columns('name', 'id').filter_by(name=name).first() emails = Users.query.add_columns( 'email', 'id').filter_by(email=email_address).first() pass_short = len(password) == 0 pass_long = len(password) > 128 valid_email = validators.validate_email(request.form['email']) team_name_email_check = validators.validate_email(name) if email.check_email_is_whitelisted(email_address) is False: errors.append( "Only email addresses under {domains} may register".format( domains=get_config('domain_whitelist'))) if names: errors.append('That user name is already taken') if team_name_email_check is True: errors.append('Your user name cannot be an email address') if emails: errors.append('That email has already been used') if pass_short: errors.append('Pick a longer password') if pass_long: errors.append('Pick a shorter password') if name_len: errors.append('Pick a longer user name') if fname_len: errors.append('Pick a longer user first name') if lname_len: errors.append('Pick a longer last name') if len(errors) > 0: return render_template('register.html', errors=errors, fname=request.form['fname'], lname=request.form['lname'], name=request.form['name'], email=request.form['email'], password=request.form['password']) else: with app.app_context(): user = Users(name=name.strip(), email=email_address.lower(), password=password.strip()) db.session.add(user) db.session.commit() db.session.flush() login_user(user) # do custom registration work here fname = fname.strip() lname = lname.strip() user_email = email_address.lower() # end custom registration work if config.can_send_mail() and get_config( 'verify_emails' ): # Confirming users is enabled and we can send email. log('registrations', format= "[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}" ) email.verify_email_address(user.email) db.session.close() return redirect(url_for('auth.confirm')) else: # Don't care about confirming users if config.can_send_mail( ): # We want to notify the user that they have registered. email.sendmail( request.form['email'], "You've successfully registered for {}".format( get_config('ctf_name'))) log('registrations', "[{date}] {ip} - {name} registered with {email}") db.session.close() return redirect(request.url_root + "getStarted" + "?result=" + urllib.parse.quote_plus(web_request.text))