def add_new(): form = UserForm(request.form) if request.method == "POST" and form.validate(): if mongo_init().users.find_one({"email": form.data.get("email")}): flash("User with email {} already exist".format( form.data.get("email")), "alert-error") return render_template("add_new.html", form=form) user = add_user(**form.data) history = { "registrationid": user["registrationid"], "passed_by": None, "cancelled_by": None, "created_by": g.user["username"], "when": datetime.datetime.now(), "query": None} mongo_init().history.insert(history) flash(u"User {name} ({email}) successfully registered".format( **user)) return redirect("{}?query={}".format( url_for("registration_deck"), user["registrationid"] )) return render_template( "add_new.html", form=form)
def confirm_pass(action, reg_id): query = request.args.get("query", "") users = mongo_init().users user = users.find_one({"registrationid": reg_id}) history = mongo_init().history if not user: flash("User {} not found, sorry".format(reg_id)) elif action == "confirm": user["passed"] = datetime.datetime.now().strftime("%m.%d.%Y %H:%M") history.insert({ "registrationid": reg_id, "passed_by": g.user["username"], "cancelled_by": None, "when": datetime.datetime.now(), "query": query }) flash(u"Registration successfully confirmed", "alert-success") elif action == "cancel": history.insert({ "registrationid": reg_id, "passed_by": None, "cancelled_by": g.user["username"], "when": datetime.datetime.now(), "query": query }) user["passed"] = None flash(u"Registration for {} cancelled".format(reg_id), "alert-error") users.save(user) return redirect("{}?query={}".format(url_for("registration_deck"), query))
def add_new(): form = UserForm(request.form) if request.method == "POST" and form.validate(): if mongo_init().users.find_one({"email": form.data.get("email")}): flash( "User with email {} already exist".format( form.data.get("email")), "alert-error") return render_template("add_new.html", form=form) user = add_user(**form.data) history = { "registrationid": user["registrationid"], "passed_by": None, "cancelled_by": None, "created_by": g.user["username"], "when": datetime.datetime.now(), "query": None } mongo_init().history.insert(history) flash(u"User {name} ({email}) successfully registered".format(**user)) return redirect("{}?query={}".format(url_for("registration_deck"), user["registrationid"])) return render_template("add_new.html", form=form)
def sync_from_local_db(args): """ Synchronize local db with remote document """ users = mongo_init().users db = DB(args.token) client = get_auth(db) sheet, wsheet = get_worksheet(client, doc_id=REGISTRATION_DOC_ID) rows = client.get_list_feed(ID(sheet), ID(wsheet.entry[0])) last = len(rows.entry) found_users = users.find({}).sort("order", pymongo.ASCENDING) #batch = gdata.spreadsheet.SpreadsheetsCellsFeed() for num, user in enumerate(found_users): row = dict([(key, val) for key, val in user.iteritems() if key != "_id"]) order = row.pop("order", last) rows.entry[order].from_dict(row) #rows.entry[order].batch_id = BatchId('update-request') client.update(rows.entry[order]) #batch.AddUpdate(rows.entry[order]) if order >= last: last += 1 print "Synced {}".format(row.get(u"email"))
def generate_confirmation(internal_id): """ Generate PDF with confirmation """ # prepare context users = mongo_init().users user = users.find_one({"internalid": internal_id}) registration_link = REGISTRATION_URL.format(user["registrationid"]) code = generate_code(registration_link, output="build/codes/{}.png".format(internal_id)) value_or_empty = lambda key: user.get(key, "") or "" if not user.get("registrationid", None): return None badge = generate_badge(title=BADGE_TITLE, name=value_or_empty("name").strip(), company=value_or_empty("company").strip(), position=value_or_empty("position").strip(), qr_code=code, reg_id=user.get("registrationid"), output="build/{}.pdf".format(internal_id)) return badge
def sync_to_local_db(args): """ Synchronize remote document with local mongo db """ users = mongo_init().users db = DB(args.token) client = get_auth(db) sheet, wsheet = get_worksheet(client, doc_id=REGISTRATION_DOC_ID) rows = client.get_list_feed(ID(sheet), ID(wsheet.entry[0])) for num, row in enumerate(rows.entry): info = row.to_dict() avail_user = users.find_one({"email": info["email"]}) if not info["internalid"]: info["internalid"] = str(uuid.uuid4()) if not avail_user: info["order"] = num users.insert(info) print "User {email} synced".format(**info) else: print "Updating {email}".format(**info) for key, val in info.iteritems(): avail_user[key] = val print "User {email} updated".format(**info) users.save(avail_user)
def generate_confirmation(internal_id): """ Generate PDF with confirmation """ # prepare context users = mongo_init().users user = users.find_one({"internalid": internal_id}) registration_link = REGISTRATION_URL.format( user["registrationid"]) code = generate_code( registration_link, output="build/codes/{}.png".format(internal_id)) value_or_empty = lambda key: user.get(key, "") or "" if not user.get("registrationid", None): return None badge = generate_badge( title=BADGE_TITLE, name=value_or_empty("name").strip(), company=value_or_empty("company").strip(), position=value_or_empty("position").strip(), qr_code=code, reg_id=user.get("registrationid"), output="build/{}.pdf".format(internal_id)) return badge
def details(reg_id): history = mongo_init().history query = request.args.get("query", "") details = mongo_init().users.find_one({"registrationid": reg_id}) records = history.find({ "registrationid": reg_id }).sort("when", pymongo.DESCENDING) if not details: flash(u"Sorry, can't find user {}".format(reg_id)) return redirect("{}?query={}".format(url_for("registration_deck"), query)) return render_template("user_details.html", details=details, records=records)
def send_confirmation(args): db = DB(args.token) if not args.campaign: raise ValueError( u"Please, provide --campaign argument value." u"Available campaigns: {}".format(", ".join(CAMPAIGNS.values()))) confirmation_shake = args.campaign external_id = [key for key, val in CAMPAIGNS.iteritems() if val == confirmation_shake][0] collection = mongo_init().users users = collection.find({}).sort("order", pymongo.ASCENDING) total = users.count() sent = 1 sent_mails = set() for num, user in enumerate(users): name = user["name"].strip() email = user["email"].strip() status = user["notification"] user_id = user["internalid"] # avoid duplicates if email in sent_mails: print u"User with email: {} already notified".format(email) continue if status and status == confirmation_shake: print u"Confirmation request to {} already sent".format(email) sent_mails.add(email) sent += 1 continue print u"Sending Confirmation `{}` to: {} ...".format( name, confirmation_shake) # prepare context link = CONFIRMATION_URL.format(external_id, user_id) badge = generate_confirmation(user_id) if badge is None: print u"Can't generate PDF for {}".format(user_id) continue context = dict([(key, val) for key, val in user.iteritems()]) context["link"] = link # send mail send_mail(db, context, template="confirmation", files=[badge]) # updating status user["notification"] = confirmation_shake collection.save(user) print u"Sent {} of {}.".format(sent, total) sent_mails.add(email) sent += 1
def sign_in(): form = AuthForm(request.form) if request.method == "POST" and form.validate(): auth = mongo_init().auth user = auth.find_one({"username": form.data.get("username")}) if not user: flash( u"Sorry, user {username} not found".format(**form.data), "alert-error") return redirect(url_for("sign_in")) username, password = form.data.get("username"), \ form.data.get("password") md5 = hashlib.md5() md5.update(password) if user["password"] == md5.hexdigest(): session["username"] = user["username"] flash( "You're successfully authorized", "alert-success") return redirect(url_for("registration_deck")) return redirect(url_for("registration_deck")) return render_template("auth.html", form=form)
def sign_in(): form = AuthForm(request.form) if request.method == "POST" and form.validate(): auth = mongo_init().auth user = auth.find_one({"username": form.data.get("username")}) if not user: flash(u"Sorry, user {username} not found".format(**form.data), "alert-error") return redirect(url_for("sign_in")) username, password = form.data.get("username"), \ form.data.get("password") md5 = hashlib.md5() md5.update(password) if user["password"] == md5.hexdigest(): session["username"] = user["username"] flash("You're successfully authorized", "alert-success") return redirect(url_for("registration_deck")) return redirect(url_for("registration_deck")) return render_template("auth.html", form=form)
def registration_deck(): users_c = mongo_init().users query = request.args.get("query", "") stats = { "passed": users_c.find({"passed": {"$ne": None}}).count(), "total": users_c.find({}).count(), "confirmed_shake1": users_c.find({"confirmationshake1": { "$ne": None}}).count(), "confirmed_shake2": users_c.find({"confirmationshake2": { "$ne": None}}).count(), } if not query: return render_template("deck.html", stats=stats) users = users_c.find({ "$or": [ {"name": {"$regex": query}}, {"registrationid": {"$regex": query}}, {"company": {"$regex": query}}, {"email": {"$regex": query}} ] }) return render_template( "deck.html", users=users, query=query, stats=stats)
def details(reg_id): history = mongo_init().history query = request.args.get("query", "") details = mongo_init().users.find_one({ "registrationid": reg_id}) records = history.find({ "registrationid": reg_id}).sort("when", pymongo.DESCENDING) if not details: flash(u"Sorry, can't find user {}".format(reg_id)) return redirect("{}?query={}".format( url_for("registration_deck"), query)) return render_template( "user_details.html", details=details, records=records)
def users(args): """ List of users """ auth = mongo_init().auth users = auth.find({}).sort("username", pymongo.ASCENDING) for user in users: print "User: {username}".format(**user)
def wrapper(*a, **kw): login = redirect('/api/login/') if not "username" in session: return login user = mongo_init().auth.find_one({"username": session["username"]}) if not user: return login g.user = user return func(*a, **kw)
def add_user(**kwargs): # defined data structure data = dict( registrationid=None, name=None, internalid=None, timestamp=None, comments=None, company=None, confirmationshake1=None, confirmationshake2=None, email=None, passed=None, notification=None, position=None, order=None) data.update(kwargs) if not data.get("internalid"): # generate internal id data["internalid"] = str(uuid.uuid4()) if not data.get("timestamp"): # generate timestamp: 9/27/2012 9:45:15 data["timestamp"] = datetime.datetime.now().strftime( "%m/%d/%Y %H:%M:%S") if not data.get("registrationid"): # generate registration ID data["registrationid"] = REGID() if not data.get("name") or not data.get("email"): raise ValueError( "Name and Email are required fields") mongo_init().users.insert(data) return data
def wrapper(*a, **kw): login = redirect('/api/login/') if not "username" in session: return login user = mongo_init().auth.find_one({ "username": session["username"]}) if not user: return login g.user = user return func(*a, **kw)
def registration_deck(): users_c = mongo_init().users query = request.args.get("query", "") stats = { "passed": users_c.find({ "passed": { "$ne": None } }).count(), "total": users_c.find({}).count(), "confirmed_shake1": users_c.find({ "confirmationshake1": { "$ne": None } }).count(), "confirmed_shake2": users_c.find({ "confirmationshake2": { "$ne": None } }).count(), } if not query: return render_template("deck.html", stats=stats) users = users_c.find({ "$or": [{ "name": { "$regex": query } }, { "registrationid": { "$regex": query } }, { "company": { "$regex": query } }, { "email": { "$regex": query } }] }) return render_template("deck.html", users=users, query=query, stats=stats)
def add_user(**kwargs): # defined data structure data = dict(registrationid=None, name=None, internalid=None, timestamp=None, comments=None, company=None, confirmationshake1=None, confirmationshake2=None, email=None, passed=None, notification=None, position=None, order=None) data.update(kwargs) if not data.get("internalid"): # generate internal id data["internalid"] = str(uuid.uuid4()) if not data.get("timestamp"): # generate timestamp: 9/27/2012 9:45:15 data["timestamp"] = datetime.datetime.now().strftime( "%m/%d/%Y %H:%M:%S") if not data.get("registrationid"): # generate registration ID data["registrationid"] = REGID() if not data.get("name") or not data.get("email"): raise ValueError("Name and Email are required fields") mongo_init().users.insert(data) return data
def confirm_pass(action, reg_id): query = request.args.get("query", "") users = mongo_init().users user = users.find_one({"registrationid": reg_id}) history = mongo_init().history if not user: flash("User {} not found, sorry".format(reg_id)) elif action == "confirm": user["passed"] = datetime.datetime.now().strftime( "%m.%d.%Y %H:%M") history.insert({ "registrationid": reg_id, "passed_by": g.user["username"], "cancelled_by": None, "when": datetime.datetime.now(), "query": query}) flash(u"Registration successfully confirmed", "alert-success") elif action == "cancel": history.insert({ "registrationid": reg_id, "passed_by": None, "cancelled_by": g.user["username"], "when": datetime.datetime.now(), "query": query}) user["passed"] = None flash(u"Registration for {} cancelled".format(reg_id), "alert-error") users.save(user) return redirect("{}?query={}".format( url_for("registration_deck"), query))
def confirm(campaign, code): if CAMPAIGNS.get(campaign) is None: flash("Sorry, campaign not found", "alert-error") return redirect(url_for("index")) users = mongo_init().users campaign = CAMPAIGNS.get(campaign) user = users.find_one({"internalid": code}) if not user: flash("Sorry, can't find such user", "alert-error") return redirect(url_for("index")) user[campaign] = "confirmed" users.save(user) flash(u"You're successfully confirmed in current campaign", "alert-success") return redirect(url_for("index"))
def add(args): """ Add new user """ auth = mongo_init().auth if not args.username or not args.password: raise ValueError("Please, enter --username " "and --password for new user") md5 = hashlib.md5() md5.update(args.password) new_user = {"username": args.username, "password": md5.hexdigest()} if auth.find_one({"username": args.username}): raise ValueError("Username `{}` already available".format( args.username)) auth.insert(new_user) print "User {username} added".format(**new_user)
def confirm(campaign, code): if CAMPAIGNS.get(campaign) is None: flash("Sorry, campaign not found", "alert-error") return redirect(url_for("index")) users = mongo_init().users campaign = CAMPAIGNS.get(campaign) user = users.find_one({"internalid": code}) if not user: flash("Sorry, can't find such user", "alert-error") return redirect(url_for("index")) user[campaign] = "confirmed" users.save(user) flash( u"You're successfully confirmed in current campaign", "alert-success") return redirect(url_for("index"))
def change(args): """ Change password """ auth = mongo_init().auth if not args.username or not args.password: raise ValueError("Please, enter --username " "and --password for new user") user = auth.find_one({"username": args.username}) if not user: raise ValueError("Username `{}` not exist yet".format(args.username)) md5 = hashlib.md5() md5.update(args.password) user["password"] = md5.hexdigest() auth.save(user) print "Password for `{username}` changed".format(**user)
def change(args): """ Change password """ auth = mongo_init().auth if not args.username or not args.password: raise ValueError("Please, enter --username " "and --password for new user") user = auth.find_one({"username": args.username}) if not user: raise ValueError("Username `{}` not exist yet".format( args.username)) md5 = hashlib.md5() md5.update(args.password) user["password"] = md5.hexdigest() auth.save(user) print "Password for `{username}` changed".format(**user)
def add(args): """ Add new user """ auth = mongo_init().auth if not args.username or not args.password: raise ValueError("Please, enter --username " "and --password for new user") md5 = hashlib.md5() md5.update(args.password) new_user = { "username": args.username, "password": md5.hexdigest() } if auth.find_one({"username": args.username}): raise ValueError("Username `{}` already available".format( args.username)) auth.insert(new_user) print "User {username} added".format(**new_user)
def send_confirmation(args): db = DB(args.token) if not args.campaign: raise ValueError(u"Please, provide --campaign argument value." u"Available campaigns: {}".format(", ".join( CAMPAIGNS.values()))) confirmation_shake = args.campaign external_id = [ key for key, val in CAMPAIGNS.iteritems() if val == confirmation_shake ][0] collection = mongo_init().users users = collection.find({}).sort("order", pymongo.ASCENDING) total = users.count() sent = 1 sent_mails = set() for num, user in enumerate(users): name = user["name"].strip() email = user["email"].strip() status = user["notification"] user_id = user["internalid"] # avoid duplicates if email in sent_mails: print u"User with email: {} already notified".format(email) continue if status and status == confirmation_shake: print u"Confirmation request to {} already sent".format(email) sent_mails.add(email) sent += 1 continue print u"Sending Confirmation `{}` to: {} ...".format( name, confirmation_shake) # prepare context link = CONFIRMATION_URL.format(external_id, user_id) badge = generate_confirmation(user_id) if badge is None: print u"Can't generate PDF for {}".format(user_id) continue context = dict([(key, val) for key, val in user.iteritems()]) context["link"] = link # send mail send_mail(db, context, template="confirmation", files=[badge]) # updating status user["notification"] = confirmation_shake collection.save(user) print u"Sent {} of {}.".format(sent, total) sent_mails.add(email) sent += 1