Beispiel #1
0
def login():
  """Handles logging in to Drawrawr"""
  if request.method == 'POST':
    required_parameters = ["username","password"]
    if not util.all_in_list(required_parameters, request.form):
      return "0" #ERROR, A required form element wasn't found
    user_result = users_model.get_one({'lowername' : request.form['username'].lower() })
    if not user_result:
      return "2" # No username match
    if cryptography.encrypt_password(request.form['password'], True) != user_result['password']: 
      return "3" # No password match
    session['username'] = user_result['username']
    session['password'] = user_result['password']
    session.permanent = True
    # Add the user's IP to the front of the list of his IPs
    ip = user_result["ip"]
    try: ip.remove(request.remote_addr)
    except ValueError: pass
    ip.insert(0,request.remote_addr)
    users_model.update({"lowername": user_result['lowername']}, {"ip": ip})
    return "1"
Beispiel #2
0
def settings():
  """The user's settings page. Used for changing their profile, account settings, and homepage."""
  if g.logged_in_user:
    if request.method == 'GET':
      if config.beta_key: beta_keys = beta_pass_model.get({"owner" : g.logged_in_user["username"] })
      else: beta_keys = None
      return render_template("settings.html", beta_keys = beta_keys)
    elif request.method == 'POST':
      # User Messages
      messages = []
      # User Icon
      icon = request.files['icon_upload']
      if icon:
        print icon.content_length
        if not icon.content_length <= config.max_icon_size:
          flash(config.file_size_error + "Your icon must be at most " + config.max_icon_size_text + ". ")
        else:
          if not util.allowed_file(icon.filename,config.icon_extensions):
            flash(config.file_type_error + "The allowed extensions are " + util.print_list(config.icon_extensions) + ". ")
          else: 
            try: os.remove(os.path.join(config.icons_dir, g.logged_in_user['lowername'] + "." + g.logged_in_user["icon"]))
            except: 
              if config.logging: logging.warning("Couldn't remove user \"" + g.logged_in_user['username']+ "\"'s old icon while attempting to upload a new icon. ")
            fileName = g.logged_in_user['lowername']
            fileType = util.fileType(icon.filename)
            if fileType.lower() == "jpg": fileType = "jpeg" # Change filetype for PIL
            (mimetype,i) = mimetypes.guess_type(icon.filename)
            file_location = os.path.join(config.icons_dir, fileName)
            users_model.update({"lowername": g.logged_in_user['lowername']}, {"icon": fileType} )
            icon.save(file_location)
            image = Image.open(file_location)
            resized = image.resize(config.icon_size, Image.ANTIALIAS)
            resized.save(file_location, fileType, quality=100)
            storage.push(file_location, file_location, mimetype = mimetype )
            messages.append("User Icon")
      # Password
      if request.form["change_pass_current"] and request.form["change_pass_new_1"] and request.form["change_pass_new_2"]:
        if cryptography.encrypt_password(request.form["change_pass_current"], True) != g.logged_in_user['password']:
          flash("The new password you gave didn't match the one in the database! ):")
        elif request.form["change_pass_new_1"] != request.form["change_pass_new_2"]:
          flash("The new passwords you gave don't match! Try retyping them carefully. ")
        else:
          hashed = cryptography.encrypt_password(request.form['change_pass_new_1'], True)
          users_model.update({"_id": g.logged_in_user['_id']}, {"password": hashed} )
          session['password']=hashed
          messages.append("Password")
      # Gender
      if request.form["change_gender"] != g.logged_in_user["gender"]:
        users_model.update({"_id": g.logged_in_user['_id']}, {"gender": request.form["change_gender"] })
        messages.append("Gender")
      # Location
      if request.form["change_latitude"] != str(g.logged_in_user["latitude"]) or request.form["change_longitude"] != str(g.logged_in_user["longitude"]):
        try:
          latFloat = float(request.form["change_latitude"])
          lonFloat = float(request.form["change_longitude"])
          users_model.update({"_id": g.logged_in_user['_id']}, {"latitude": latFloat, "longitude": lonFloat } )
          messages.append("Location")
        except ValueError:
          flash("The locations you gave were invalid latitude and longitude coordinates! ): ")
      # Profile
      if request.form["change_profile"] != g.logged_in_user["profile"]:
        users_model.update({"_id": g.logged_in_user['_id']}, {"profile": request.form["change_profile"], "code_profile": usercode.parse(request.form["change_profile"]) })
        messages.append("Profile")
      # Color Theme
      if request.form["change_color_theme"] != g.logged_in_user["theme"]:
        users_model.update({"_id": g.logged_in_user['_id']}, {"theme": request.form["change_color_theme"]} )
        messages.append("Color Theme")
      # Layout
      l1 = util.url_decode(request.form["change_layout"])
      l2 = util.url_decode(request.form["change_layout_order"])
      for key in l2: l2[key] = int(l2[key]) # Converts orderings to integers
      layout = util.conc_dict_values(l1,l2)
      if not util.compare_dicts(layout, g.logged_in_user["layout"]):
        if util.compare_dict_keys(layout, g.logged_in_user["layout"]):
          layout_to_push = {}
          for key in layout:
            layout_to_push["layout." + key] = layout[key]
          users_model.update({"_id": g.logged_in_user['_id']}, layout_to_push)
          messages.append("Layout")
      return render_template("settings_success.html",messages=messages,len=len)
  else: abort(401)
Beispiel #3
0
def signup(): 
  """Handles member signup requests"""
  # Error Handling
  required_parameters = ['username','password1','password2']
  if config.captcha: required_parameters += ['recaptcha_challenge_field','recaptcha_response_field']
  if config.beta_key: required_parameters += ['beta_code']
  if not util.all_in_list(required_parameters, request.form):
    return "0" #ERROR, A required form element wasn't found
  username_len = len(request.form['username'])
  if users_model.username_taken(request.form['username']) or username_len == 0 or username_len > 30:
    return "2" #ERROR, User doesn't exist or username is too small
  if request.form['password1'] != request.form['password2'] or not request.form['password1']:
    return "3" #ERROR, Passwords don't match
  if not 'tos_agree' in request.form:
    return "4" #ERROR, Terms of Service wasn't checked
  if config.captcha and not captcha.check(request.form['recaptcha_challenge_field'], request.form['recaptcha_response_field'],config.captcha_secret_key,request.remote_addr):
    return "5" #ERROR, Captcha Fail
  if config.beta_key:
    beta_key = beta_pass_model.check(request.form["beta_code"])
    if not beta_key:
      return "6" #ERROR, Beta Code Fail
  if g.logged_in_user:
    return "7" #ERROR, User is already logged in
  else: beta_key = None
  # Add the user to the database
  hashed = cryptography.encrypt_password(request.form['password1'], True)
  icon_filepath = os.path.join(config.icons_dir, request.form['username'].lower())
  storage.push("static/images/newby_icon.png", icon_filepath, mimetype="image/png")
  if not config.using_S3: shutil.copyfile("static/images/newby_icon.png", icon_filepath)
  users_model.insert({
    "username"    : request.form['username']
  , "lowername"   : request.form['username'].lower()
  , "password"    : hashed
  , "email"       : None #request.form['email']
  , "ip"          : [request.remote_addr]
  , "dob"         : None
  , "beta_key"    : beta_key
  , "beta_keys"   : config.starting_beta_keys
  , "date_joined" : datetime.datetime.today()
  , "show_ads"    : True
  , "layout"      : {
      # [CARDINAL LOCATION, ORDERING]
      # t == top; l == left; r == right; b == bottom; h == hidden
      "profile"   : ["t",0]
    , "gallery"   : ["l",0]
    , "watches"   : ["r",0]
    , "comments"  : ["b",0]
    , "nearby"    : ["r",1]
    , "journal"   : ["l",1]
    , "shout"     : ["h",0]
    , "friends"   : ["h",0]
    , "awards"    : ["h",0]
    , "shop"      : ["h",0]
    , "favorites" : ["h",0]
    , "tips"      : ["h",0]
    , "chars"     : ["h",0]
    , "playlist"  : ["h",0]
    }
  , "permissions" : {
      "delete_comments"    : True
    , "edit_art"           : True
    , "delete_art"         : True
    , "delete_journal"     : True
    , "ban_users"          : True
    , "make_props"         : True
    , "vote"               : True
    , "generate_beta_pass" : True
    , "crop_art"           : True
    }
  , "latitude"     : None
  , "longitude"    : None
  , "theme"        : "default"
  , "profile"      : ""
  , "code_profile" : ""
  , "page_views"   : 0
  , "watchers"     : []
  , "bground"      : None
  , "icon"         : "png"
  , "glued"        : 1
    # m == Male; f == Female; h == Hide Gender
  , "gender"       : "h"
  }) 
  session['username'] = request.form['username']
  session['password'] = hashed
  session.permanent = True
  return "1" #SUCCESS