Example #1
0
def sendVerificationMail(db, user, email_id=None):
    cursor = db.cursor()

    if email_id is None:
        cursor.execute("""SELECT email
                            FROM users
                           WHERE id=%s""",
                       (user.id,))

        email_id, = cursor.fetchone()

    cursor.execute("""SELECT email, verification_token
                        FROM useremails
                       WHERE id=%s""",
                   (email_id,))

    email, verification_token = cursor.fetchone()

    if verification_token is None:
        verification_token = auth.getToken(encode=base64.b16encode)

        with db.updating_cursor("useremails") as cursor:
            cursor.execute("""UPDATE useremails
                                 SET verification_token=%s
                               WHERE id=%s""",
                           (verification_token, email_id))

    if configuration.base.ACCESS_SCHEME == "http":
        protocol = "http"
    else:
        protocol = "https"

    administrators = dbutils.getAdministratorContacts(db, indent=2)

    if administrators:
        administrators = ":\n\n%s" % administrators
    else:
        administrators = "."

    recipients = [mailutils.User(user.name, email, user.fullname)]
    subject = "[Critic] Please verify your email: %s" % email
    body = textutils.reflow("""
This is a message from the Critic code review system at %(hostname)s.  The user
'%(username)s' on this system has added this email address to his/her account.
If this is you, please confirm this by following this link:

  %(url_prefix)s/verifyemail?email=%(email)s&token=%(verification_token)s

If this is not you, you can safely ignore this email.  If you wish to report
abuse, please contact the Critic system's administrators%(administrators)s
""" % { "hostname": configuration.base.HOSTNAME,
        "username": user.name,
        "email": email,
        "url_prefix": "%s://%s" % (protocol, configuration.base.HOSTNAME),
        "verification_token": verification_token,
        "administrators": administrators })

    mailutils.sendMessage(recipients, subject, body)
Example #2
0
def sendVerificationMail(db, user, email_id=None):
    cursor = db.cursor()

    if email_id is None:
        cursor.execute("""SELECT email
                            FROM users
                           WHERE id=%s""",
                       (user.id,))

        email_id, = cursor.fetchone()

    cursor.execute("""SELECT email, verification_token
                        FROM useremails
                       WHERE id=%s""",
                   (email_id,))

    email, verification_token = cursor.fetchone()

    if verification_token is None:
        verification_token = auth.getToken(encode=base64.b16encode)

        cursor.execute("""UPDATE useremails
                             SET verification_token=%s
                           WHERE id=%s""",
                       (verification_token, email_id))

    if configuration.base.ACCESS_SCHEME == "http":
        protocol = "http"
    else:
        protocol = "https"

    administrators = dbutils.getAdministratorContacts(db, indent=2)

    if administrators:
        administrators = ":\n\n%s" % administrators
    else:
        administrators = "."

    recipients = [mailutils.User(user.name, email, user.fullname)]
    subject = "[Critic] Please verify your email: %s" % email
    body = textutils.reflow("""
This is a message from the Critic code review system at %(hostname)s.  The user
'%(username)s' on this system has added this email address to his/her account.
If this is you, please confirm this by following this link:

  %(url_prefix)s/verifyemail?email=%(email)s&token=%(verification_token)s

If this is not you, you can safely ignore this email.  If you wish to report
abuse, please contact the Critic system's administrators%(administrators)s
""" % { "hostname": configuration.base.HOSTNAME,
        "username": user.name,
        "email": email,
        "url_prefix": "%s://%s" % (protocol, configuration.base.HOSTNAME),
        "verification_token": verification_token,
        "administrators": administrators })

    mailutils.sendMessage(recipients, subject, body)
Example #3
0
def signup(request):
    try:
        user = User.objects.create(username=request.data['username'],
                                   password=auth.hash(
                                       request.data['password']))
    except:
        return JsonResponse(0, status=417, safe=False)
    user.save()
    user = user.toDict()
    user['authToken'] = auth.getToken(user)
    return JsonResponse(user, safe=False)
Example #4
0
    def createAccessToken(self, access_type, title, callback=None):
        import auth
        import base64

        from accesstoken import CreatedAccessToken

        critic = self.transaction.critic

        if access_type != "user":
            api.PermissionDenied.raiseUnlessAdministrator(critic)

        user_id = self.user.id if access_type == "user" else None

        part1 = auth.getToken(encode=base64.b64encode, length=12)
        part2 = auth.getToken(encode=base64.b64encode, length=21)

        access_token = CreatedAccessToken(
            critic, self.user if access_type == "user" else None, callback)

        self.transaction.tables.update(("accesstokens",
                                        "accesscontrolprofiles"))
        self.transaction.items.append(
            api.transaction.Query(
                """INSERT
                     INTO accesstokens (access_type, uid, part1, part2, title)
                   VALUES (%s, %s, %s, %s, %s)
                RETURNING id""",
                (access_type, user_id, part1, part2, title),
                collector=access_token))
        self.transaction.items.append(
            api.transaction.Query(
                """INSERT
                     INTO accesscontrolprofiles (access_token)
                   VALUES (%s)
                RETURNING id""",
                (access_token,),
                collector=access_token.profile))

        return access_token
Example #5
0
def createSessionId(db, req, user, authentication_labels=None):
    sid = auth.getToken()
    if authentication_labels:
        labels = "|".join(sorted(authentication_labels))
    else:
        labels = ""

    with db.updating_cursor("usersessions") as cursor:
        cursor.execute("""INSERT INTO usersessions (key, uid, labels)
                               VALUES (%s, %s, %s)""",
                       (sid, user.id, labels))

    req.setCookie("sid", sid, secure=True)
    req.setCookie("has_sid", "1")
Example #6
0
def createSessionId(db, req, user, authentication_labels=None):
    sid = auth.getToken()
    if authentication_labels:
        labels = "|".join(sorted(authentication_labels))
    else:
        labels = ""

    with db.updating_cursor("usersessions") as cursor:
        cursor.execute(
            """INSERT INTO usersessions (key, uid, labels)
                               VALUES (%s, %s, %s)""", (sid, user.id, labels))

    req.setCookie("sid", sid, secure=True)
    req.setCookie("has_sid", "1")
Example #7
0
    def start(self, db, req, target_url=None):
        state = auth.getToken()

        authorize_url = self.getAuthorizeURL(state)

        if authorize_url is None:
            return None

        if target_url is None:
            target_url = req.getParameter("target", None)

        with db.updating_cursor("oauthstates") as cursor:
            cursor.execute(
                """INSERT INTO oauthstates (state, url)
                                   VALUES (%s, %s)""", (state, target_url))

        return authorize_url
Example #8
0
 def findMetrics(self, query):
   payload = {'query': query}
   headers = auth.headers()
   if auth.isActive():
     headers['X-Auth-Token'] = auth.getToken()
   r = requests.get("%s/v2.0/%s/metrics/search" % (self.host, self.tenant), params=payload, headers=headers)
   if r.status_code is not 200:
     print str(r.status_code) + ' in findMetrics ' + r.text
     return []
   else:
     try:
       return r.json()
     except TypeError:
       # we need to parse the json ourselves.
       return json.loads(r.text)
     except ValueError:
       return ['there was an error']
Example #9
0
    def start(self, db, req, target_url=None):
        state = auth.getToken()

        authorize_url = self.getAuthorizeURL(state)

        if authorize_url is None:
            return None

        if target_url is None:
            target_url = req.getParameter("target", None)

        with db.updating_cursor("oauthstates") as cursor:
            cursor.execute("""INSERT INTO oauthstates (state, url)
                                   VALUES (%s, %s)""",
                           (state, target_url))

        return authorize_url
Example #10
0
  def getValues(self, metric, start, stop):
    # make an educated guess about the likely number of data points returned.
    num_points = (stop - start) / 60
    res = 'FULL'

    if num_points > 800:
      num_points = (stop - start) / SECONDS_IN_5MIN
      res = 'MIN5'
    if num_points > 800:
      num_points = (stop - start) / SECONDS_IN_20MIN
      res = 'MIN20'
    if num_points > 800:
      num_points = (stop - start) / SECONDS_IN_60MIN
      res = 'MIN60'
    if num_points > 800:
      num_points = (stop - start) / SECONDS_IN_240MIN
      res = 'MIN240'
    if num_points > 800:
      num_points = (stop - start) / SECONDS_IN_1440MIN
      res = 'MIN1440'

    payload = {
      'from': start * 1000,
      'to': stop * 1000,
      'resolution': res
    }
    #print 'USING RES ' + res
    headers = auth.headers()
    if auth.isActive():
      headers['X-Auth-Token'] = auth.getToken()
    r = requests.get("%s/v2.0/%s/views/%s" % (self.host, self.tenant, metric), params=payload, headers=headers)
    if r.status_code is not 200:
      print str(r.status_code) + ' in getValues ' + r.text
      return {'values': []}
    else:
      try:
        return r.json()['values']
      except TypeError:
        # parse that json yo
        return json.loads(r.text)['values']
      except ValueError:
        print 'ValueError in getValues'
        return {'values': []}
Example #11
0
    def mutate(self, info, firstName, lastName, email_address, password):
        try:
            passwordHash = auth.generatePassword(password)

            # TODO: validate info
            response = requests.post("{}/users".format(config.HARAMBE_DATA_SERVICE_ENDPOINT), json={
                "firstName": firstName,
                "lastName": lastName,
                "email_address": email_address,
                "password": passwordHash
            })

            assert(response.status_code == 200), "Could not create user"

            # get token
            tokenString = auth.getToken(email_address, password)
            return RegisterUser(token=tokenString)
        except AssertionError as e:
            raise graphql.GraphQLError(e)
Example #12
0
    def start(self, db, req, target_url=None):
        cursor = db.cursor()
        state = auth.getToken()

        authorize_url = self.getAuthorizeURL(state)

        if authorize_url is None:
            return False

        if target_url is None:
            target_url = req.getParameter("target", None)

        cursor.execute("""INSERT INTO oauthstates (state, url)
                               VALUES (%s, %s)""",
                       (state, target_url))

        req.setStatus(302)
        req.addResponseHeader("Location", authorize_url)
        req.start()

        db.commit()

        return True
Example #13
0
    def start(self, db, req, target_url=None):
        cursor = db.cursor()
        state = auth.getToken()

        authorize_url = self.getAuthorizeURL(state)

        if authorize_url is None:
            return False

        if target_url is None:
            target_url = req.getParameter("target", None)

        cursor.execute(
            """INSERT INTO oauthstates (state, url)
                               VALUES (%s, %s)""", (state, target_url))

        req.setStatus(302)
        req.addResponseHeader("Location", authorize_url)
        req.start()

        db.commit()

        return True
Example #14
0
    def finish(self, db, req):
        if req.method != "GET":
            raise auth.InvalidRequest

        code = req.getParameter("code", default=None)
        state = req.getParameter("state", default=None)

        if code is None or state is None:
            raise auth.InvalidRequest("Missing parameter(s)")

        cursor = db.cursor()
        cursor.execute("""SELECT url
                            FROM oauthstates
                           WHERE state=%s""",
                       (state,))

        row = cursor.fetchone()

        if not row:
            raise auth.InvalidRequest("Invalid OAuth state: %s" % state)

        (target_url,) = row

        access_token = self.getAccessToken(code)

        if access_token is None:
            raise auth.Failure("failed to get access token")

        user_data = self.getUserData(access_token)

        if user_data is None:
            raise auth.Failure("failed to get user data")

        account = textutils.encode(user_data["account"])
        username = textutils.encode(user_data["username"])
        email = user_data["email"]
        email = textutils.encode(email) if email else None
        fullname = textutils.encode(user_data.get("fullname", username))

        cursor.execute("""SELECT id, uid
                            FROM externalusers
                           WHERE provider=%s
                             AND account=%s""",
                       (self.name, account))

        row = cursor.fetchone()

        if not row:
            cursor.execute("""INSERT INTO externalusers (provider, account, email)
                                   VALUES (%s, %s, %s)
                                RETURNING id""",
                           (self.name, account, email))

            row = (cursor.fetchone()[0], None)

        external_user_id, user_id = row
        user = None

        if user_id is None:
            if auth.isValidUserName(username) \
                    and self.configuration.get("bypass_createuser"):
                try:
                    dbutils.User.fromName(db, username)
                except dbutils.NoSuchUser:
                    user = dbutils.User.create(db, username, fullname, email, None)
                    cursor.execute("""UPDATE externalusers
                                         SET uid=%s
                                       WHERE id=%s""",
                                   (user.id, external_user_id))
                    user.sendUserCreatedMail("wsgi[oauth/%s]" % self.name,
                                             { "provider": self.name,
                                               "account": account })
        else:
            user = dbutils.User.fromId(db, user_id)

        if user is not None:
            auth.startSession(db, req, user)
        else:
            token = auth.getToken()

            cursor.execute("""UPDATE externalusers
                                 SET token=%s
                               WHERE id=%s""",
                           (token, external_user_id))

            data = { "provider": self.name,
                     "account": account,
                     "token": token }

            if target_url:
                data["target"] = target_url
            if username:
                data["username"] = username
            if email:
                data["email"] = email
            if fullname:
                data["fullname"] = fullname

            target_url = "/createuser?%s" % urllib.urlencode(data)

        req.setStatus(302)
        req.addResponseHeader("Location", target_url or "/")
        req.start()

        db.commit()

        return True
Example #15
0
def getUserToken(code):
    TOKEN_DATA = getToken(code, SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET,
                          "{}:{}/callback/".format(SPOTIPY_REDIRECT_URI, PORT))
    return TOKEN_DATA
Example #16
0
    def finish(self, db, req):
        if req.method != "GET":
            raise auth.InvalidRequest

        code = req.getParameter("code", default=None)
        state = req.getParameter("state", default=None)

        if code is None or state is None:
            raise auth.InvalidRequest("Missing parameter(s)")

        cursor = db.cursor()
        cursor.execute(
            """SELECT url
                            FROM oauthstates
                           WHERE state=%s""", (state, ))

        row = cursor.fetchone()

        if not row:
            raise auth.InvalidRequest("Invalid OAuth state: %s" % state)

        (target_url, ) = row

        access_token = self.getAccessToken(code)

        if access_token is None:
            raise auth.Failure("failed to get access token")

        user_data = self.getUserData(access_token)

        if user_data is None:
            raise auth.Failure("failed to get user data")

        account = textutils.encode(user_data["account"])
        username = textutils.encode(user_data["username"])
        email = user_data["email"]
        email = textutils.encode(email) if email else None
        fullname = textutils.encode(user_data.get("fullname", username))

        cursor.execute(
            """SELECT id, uid
                            FROM externalusers
                           WHERE provider=%s
                             AND account=%s""", (self.name, account))

        row = cursor.fetchone()

        if row:
            external_user_id, user_id = row
        else:
            with db.updating_cursor("externalusers") as updating_cursor:
                updating_cursor.execute(
                    """INSERT INTO externalusers (provider, account, email)
                            VALUES (%s, %s, %s)
                         RETURNING id""", (self.name, account, email))
                external_user_id, = updating_cursor.fetchone()
                user_id = None

        user = None

        if user_id is not None:
            user = dbutils.User.fromId(db, user_id)
        else:
            if auth.isValidUserName(username) \
                    and self.configuration.get("bypass_createuser"):
                try:
                    dbutils.User.fromName(db, username)
                except dbutils.NoSuchUser:
                    user = dbutils.User.create(
                        db,
                        username,
                        fullname,
                        email,
                        email_verified=None,
                        external_user_id=external_user_id)
                    user.sendUserCreatedMail("wsgi[oauth/%s]" % self.name, {
                        "provider": self.name,
                        "account": account
                    })

        if user is None:
            token = auth.getToken()

            with db.updating_cursor("externalusers") as updating_cursor:
                updating_cursor.execute(
                    """UPDATE externalusers
                          SET token=%s
                        WHERE id=%s""", (token, external_user_id))

            data = {"provider": self.name, "account": account, "token": token}

            if target_url:
                data["target"] = target_url
            if username:
                data["username"] = username
            if email:
                data["email"] = email
            if fullname:
                data["fullname"] = fullname

            target_url = "/createuser?%s" % urllib.urlencode(data)

        if user is not None:
            auth.createSessionId(db, req, user)

        raise request.Found(target_url or "/")
Example #17
0
 def mutate(self, info, email_address, password):
     try:
         tokenString = auth.getToken(email_address, password)
         return LoginUser(token=tokenString)
     except AssertionError as e:
         raise graphql.GraphQLError(e)
Example #18
0
import gbwiki as gb

# As prep:
#   1. If regToken.txt exists, delete it
#   2. Get a code from https://www.giantbomb.com/app/myapp/

# Checks whether the regToken exists
tmpbool = auth.checkForRegToken()
print(tmpbool)

# Enter in the code from the myapp website
code = '8BF4B2'
print(code)

# Gets the token by exchanging it for the code
regToken = auth.getToken(code)
print(regToken)

# Stores the token in a text file
auth.storeToken(regToken)

# Checks whether the regToken exists (should be True)
tmpbool = auth.checkForRegToken()
print(tmpbool)

# Retrieves the token
check = gb.getToken()
print(check)

# Runs a GB wiki request using the retrieved token instead of a
# hard-coded one
Example #19
0
 def rpc_getToken(self, username):
     return auth.getToken(username)