Alpha Software Mobile Development Tools:   Alpha Anywhere    |   Alpha TransForm subscribe to our YouTube Channel  Follow Us on LinkedIn  Follow Us on Twitter  Follow Us on Facebook

Announcement

Collapse

The Alpha Software Forum Participation Guidelines

The Alpha Software Forum is a free forum created for Alpha Software Developer Community to ask for help, exchange ideas, and share solutions. Alpha Software strives to create an environment where all members of the community can feel safe to participate. In order to ensure the Alpha Software Forum is a place where all feel welcome, forum participants are expected to behave as follows:
  • Be professional in your conduct
  • Be kind to others
  • Be constructive when giving feedback
  • Be open to new ideas and suggestions
  • Stay on topic


Be sure all comments and threads you post are respectful. Posts that contain any of the following content will be considered a violation of your agreement as a member of the Alpha Software Forum Community and will be moderated:
  • Spam.
  • Vulgar language.
  • Quotes from private conversations without permission, including pricing and other sales related discussions.
  • Personal attacks, insults, or subtle put-downs.
  • Harassment, bullying, threatening, mocking, shaming, or deriding anyone.
  • Sexist, racist, homophobic, transphobic, ableist, or otherwise discriminatory jokes and language.
  • Sexually explicit or violent material, links, or language.
  • Pirated, hacked, or copyright-infringing material.
  • Encouraging of others to engage in the above behaviors.


If a thread or post is found to contain any of the content outlined above, a moderator may choose to take one of the following actions:
  • Remove the Post or Thread - the content is removed from the forum.
  • Place the User in Moderation - all posts and new threads must be approved by a moderator before they are posted.
  • Temporarily Ban the User - user is banned from forum for a period of time.
  • Permanently Ban the User - user is permanently banned from the forum.


Moderators may also rename posts and threads if they are too generic or do not property reflect the content.

Moderators may move threads if they have been posted in the incorrect forum.

Threads/Posts questioning specific moderator decisions or actions (such as "why was a user banned?") are not allowed and will be removed.

The owners of Alpha Software Corporation (Forum Owner) reserve the right to remove, edit, move, or close any thread for any reason; or ban any forum member without notice, reason, or explanation.

Community members are encouraged to click the "Report Post" icon in the lower left of a given post if they feel the post is in violation of the rules. This will alert the Moderators to take a look.

Alpha Software Corporation may amend the guidelines from time to time and may also vary the procedures it sets out where appropriate in a particular case. Your agreement to comply with the guidelines will be deemed agreement to any changes to it.



Bonus TIPS for Successful Posting

Try a Search First
It is highly recommended that a Search be done on your topic before posting, as many questions have been answered in prior posts. As with any search engine, the shorter the search term, the more "hits" will be returned, but the more specific the search term is, the greater the relevance of those "hits". Searching for "table" might well return every message on the board while "tablesum" would greatly restrict the number of messages returned.

When you do post
First, make sure you are posting your question in the correct forum. For example, if you post an issue regarding Desktop applications on the Mobile & Browser Applications board , not only will your question not be seen by the appropriate audience, it may also be removed or relocated.

The more detail you provide about your problem or question, the more likely someone is to understand your request and be able to help. A sample database with a minimum of records (and its support files, zipped together) will make it much easier to diagnose issues with your application. Screen shots of error messages are especially helpful.

When explaining how to reproduce your problem, please be as detailed as possible. Describe every step, click-by-click and keypress-by-keypress. Otherwise when others try to duplicate your problem, they may do something slightly different and end up with different results.

A note about attachments
You may only attach one file to each message. Attachment file size is limited to 2MB. If you need to include several files, you may do so by zipping them into a single archive.

If you forgot to attach your files to your post, please do NOT create a new thread. Instead, reply to your original message and attach the file there.

When attaching screen shots, it is best to attach an image file (.BMP, .JPG, .GIF, .PNG, etc.) or a zip file of several images, as opposed to a Word document containing the screen shots. Because Word documents are prone to viruses, many message board users will not open your Word file, therefore limiting their ability to help you.

Similarly, if you are uploading a zipped archive, you should simply create a .ZIP file and not a self-extracting .EXE as many users will not run your EXE file.
See more
See less

Oauth for Google API

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Oauth for Google API

    Has anyone done the work / have a function / close to this to get an Oauth2 token for a Google API? I *might* be able to figure it out but not so far and really need to cut my time loss on this one. Yes, I have the key and secret - just need to figure out how to get the token.

    Thanks
    -Steve
    sigpic

    #2
    Re: Oauth for Google API

    Well, yes, this can be done. And I've paid someone else to build a UDF for similar purposes. I've asked him if he's available to do this one for us, but wanted to check here first in case someone had done it and was willing to share.

    And I don't want a dummy auth code - I need one for a full production app.
    -Steve
    sigpic

    Comment


      #3
      Re: Oauth for Google API

      I've done it. I've always meant to get around to publishing it, but I never have taken out my site specific code. Basically, you can take this class and change the 'dim sql' commands to be where you'll store the credentials. You can probably remove the setregionnum function stuff. The setAuthConfig json file can be found in your API console. This 'should' get you started.

      Edit: Actually the setregionnum stuff is what 'links' the identity of the entity in alpha with the oauth code. You'll need to adjust that to your use case.
      Basically, you'll need to look at these functions: setRegionNum, setRefreshToken, setAccessToken, getAccessToken, and openConnection

      Code:
      define class apollo::google::auth
      
          '//Authentication
          '// This auth class uses refresh tokens
          '// Flow:
          '    1) .setAuthConfig("c:\data\*****.json")
          '    2) .setRegionNum(convert_type(Context.Session.Variables.regionnum,"N"))
          '    3) .setScopes("https://www.googleapis.com/auth/admin.directory.user.readonly")
          '    4) .setRedirectUri(getRedirectURIFromJson(3))
      
      
          'Settings is the JSON file loaded into a pointer
          dim settings as p
          'Scope is a space delimited list of scopes as found in https://developers.google.com/identity/protocols/googlescopes
          dim scope as c = ""
          'Access Token
          dim access_token as c = ""
          'Access Token Expiration
          dim access_token_expires as t
          'Refresh Token
          dim refresh_token as c = ""
          'Redirect URI
          dim redirect_uri as c = ""
          'Connection to SQL
          dim cn as sql::Connection
          'Region
          dim region_num as n
          
          function setRegionNum as l (num as n)
              self.region_num = num
              setRegionNum = .t.
          end function
          
          function setAuthConfig as l (file as c)
              'This function loads the secret json file supplied by Google
              if .not. file.exists(file) then
                  'File doesn't exist
                  setAuthConfig = .f.
                  end
              end if
              
              dim json as c = get_from_file(file)
              self.settings = json_parse(json).web
                      
              setAuthConfig = .t.
          end function
      
          function setScopes as l (scopes as c)
              'This function sets the scope variable
              self.scope = scopes
              setScopes = .t.
          end function
          
          function setRedirectUri as l (uri as c)
              'Set's the Redirect URI for this object
              'Check Redirect URI to make sure it's in the settings object
              dim check as l = .f.
              for each path in self.settings.redirect_uris
                  if uri == path.Value then
                      check = .t.
                      exit for
                  end if
              next
              
              if check then
                  self.redirect_uri = uri
                  setRedirectUri = .t.
              else
                  self.redirect_uri = "Redirect URI must be listed in Settings JSON, please add it to the Google Console, then download a new JSON file"
                  setRedirectUri = .f.
              end if
          end function
          
          function getRedirectURIFromJson as c (index as n)
              'This function retrieves the uri from the json file, given the index
              getRedirectURIFromJson = self.settings.redirect_uris[index]
          end function
          
          function createAuthUrl as c (state as c = "")
              'This function creates the oAuth2 URL
              'References
              'https://developers.google.com/accounts/docs/OAuth2WebServer
              dim query as extension::URIQuery
              
              query.SetData("response_type","code")
              query.SetData("client_id",self.settings.client_id)
              query.SetData("scope",self.scope)
              query.SetData("access_type","offline")
              'Keep already granted scopes
              query.SetData("include_granted_scopes","false")
              query.SetData("approval_prompt","force")
              query.SetData("redirect_uri",self.redirect_uri)
      
              if state <> ""
                  query.SetData("state",state)
              end if
      
              createAuthUrl = self.settings.auth_uri + "?" + query.BuildURIQuery()
          end function
          
          function fetchTokensWithAuthCode as l (code as c)
              'This function should be the only public query function, as it's called from the redirect_uri
              'This function exchanges an AuthCode for Access Token
              '(It will also return the refresh_token if access_type was set to offline [which it was])
              dim query as extension::URIQuery
      
              query.SetData("code",code)
              query.SetData("client_id",self.settings.client_id)
              query.SetData("client_secret",urlencode(self.settings.client_secret))
              query.SetData("redirect_uri",self.redirect_uri)
              query.SetData("grant_type","authorization_code")
              
              'We don't need authentication with this one, so just use http_post()
              dim response as p = http_post(self.settings.token_uri,query.BuildURIQuery())
              if response.parsed_headers.status_code <> 200 then
                  'Error
                  throw("critical","fetchAccessTokenWithAuthCode()",response.body)
                  fetchTokensWithAuthCode = .f.
                  end
              end if
              
              'Success, we should save the tokens
              dim google as p = json_parse(response.body)
              if .not. self.setAccessToken(google.access_token,now()+google.expires_in) then
                  'Access Token not saved
              end if
              if .not. self.setRefreshToken(google.refresh_token) then
                  'Refresh Token not saved
              end if
              
              fetchTokensWithAuthCode = .t.
          end function 
          
          function setRefreshToken as l (token as c)
              'This function saves the refresh token to the database
              'First, save the refresh token to the object
              self.refresh_token = token
              'Then save it to the database
              dim sql as c = "UPDATE gen_branchdata SET gdata_refresh_token = :token WHERE CompanyID=:regionnum"
              dim args as sql::Arguments
              args.set("token",token)
              args.set("regionnum",self.region_num)
              
              if .not. self.cn.IsOpen then
                  self.openConnection()
              end if
              
              if self.cn.Execute(sql,args) then
                  saveRefreshToken = .t.
              else
                  throw("error","setRefreshToken()",cn.CallResult.text+crlf()+cleanSQL(sql,args))
                  saveRefreshToken = .f.
              end if
          end function
          
          function setAccessToken as l (token as c, expires as t)
              'Save the Access token and expires time
              'First save to the object
              self.access_token = token
              self.access_token_expires = expires
              'Now the DB
              dim sql as c = "UPDATE gen_branchdata SET gdata_token_value = :token, gdata_token_time = :expires WHERE CompanyID=:regionnum"
              dim args as sql::Arguments
              args.set("token",token)
              args.set("regionnum",self.region_num)
              args.set("expires",expires)
              
              if .not. self.cn.IsOpen then
                  self.openConnection()
              end if
              
              if self.cn.Execute(sql,args) then
                  setAccessToken = .t.
              else
                  throw("error","setAccessToken()",cn.CallResult.text+crlf()+cleanSQL(sql,args))
                  setAccessToken = .f.
              end if
          end function
          
          function getAccessToken as c ()
              'Retrieve the Access token
              'First, check the object
              dim now as t = now()
              if self.access_token_expires <> "" then
                  'Expires is set, check to see if it's expired
                  if now < self.access_token_expires then
                      'It's a good token, return it
                      getAccessToken = self.access_token
                      end
                  end if
              end if
              
              'It's either not in the object, or it's expired, let's check the database
              if .not. self.cn.IsOpen then
                  self.openConnection()
              end if
              
              dim args as sql::Arguments
              args.set("regionnum",self.region_num)
              'For optimization's sake, I'll pull the token time, the token, and the refresh, just in case
              dim sql as c = "SELECT gdata_token_time,gdata_token_value,gdata_refresh_token FROM gen_branchdata WHERE CompanyID=:regionnum"
              if self.cn.Execute(sql,args) then
                  'Check time
                  if now < convert_type(cn.ResultSet.data("gdata_token_time"),"T") then
                      'The token is not expired, set & return the token
                      'But since we got it from the db, i don't want to resave to db
                      'So we'll just set it in the object, and return
                      self.access_token = cn.ResultSet.data("gdata_token_value")
                      self.access_token_expires = cn.ResultSet.data("gdata_token_time")
                      getAccessToken = self.access_token
                      end
                  end if
                  'If we've hit this, the token is expired, let's get a new one
                  'Run getNewAccessToken()
                  if self.getNewAccessToken(cn.ResultSet.data("gdata_refresh_token")) then
                      'getNewAccessToken will save the new token to the object, just return that
                      getAccessToken = self.access_token
                  end if
              else
                  getAccessToken = "Couldn't get token from Database" + crlf() + cn.callresult.text
              end if
          end function
          
          function getNewAccessToken as l (token as c)
          ' This function get's a new access token from the refresh token
              dim query as extension::URIQuery
              
              query.SetData("refresh_token",token)
              query.SetData("client_id",self.settings.client_id)
              query.SetData("client_secret",self.settings.client_secret)
              query.SetData("grant_type","refresh_token")
              
              dim response as p = http_post(self.settings.token_uri,query.BuildURIQuery())
              if response.parsed_headers.status_code <> 200 then
                  throw("critical","getNewAccessToken",json_generate(response))
                  getNewAccessToken = .f.
                  end
              end if
              
              'Now we have a response, let's save the Access Token
              dim google as p = json_parse(response.body)
              if self.setAccessToken(google.access_token,now()+google.expires_in) then
                  getNewAccessToken = .t.
              end if
          
          end function
          
          function checkAccessToken as c ()
              
              dim host as c = "https://www.googleapis.com"
              dim method as c = "/oauth2/v1/tokeninfo"
              
              dim query as extension::URIQuery
              
              query.setData("access_token",self.getAccessToken())
              
              dim response as p = http_get(host+method+query.BuildURIQuery())
              
              checkAccessToken = response.body
              
          end function
          
          function openConnection as l ()
              openConnection = cn.open("::name::global")
          end function
          
          function closeConnection as l ()
              'Run this as your last command
              self.cn.Close()
              closeConnection = .t.
          end function
      
          function get as c (page_method as c, parameters as c = "")
              'Custom http_get function to include Auth
              dim get_settings as p
              with get_settings
                  ssl_on = .t.
                  host = "www.googleapis.com"
                  page = page_method
                  query_string = parameters
                  method = "GET"
                  header = "Authorization: Bearer "+self.getAccessToken()
              end with
              dim response as p = http_fetch(get_settings)
              get = response.body
          end function
      
          function post as c (page_method as c, payload as c)
              'Custom http_post function to inclue Auth
              dim post_settings as p
              with post_settings
                  ssl_on = .t.
                  host = "www.googleapis.com"
                  page = page_method
                  body = payload
                  method = "POST"
                  header = "Authorization: Bearer " + self.getAccessToken() + crlf() + "Content-Type: application/json"
              end with
              dim response as p = http_fetch(post_settings)
              post = response.body
          end function
          
          function delete as c (page_method as c)
              'Custom http delete function to inclue Auth
              dim delete_settings as p
              with delete_settings
                  ssl_on = .t.
                  host = "www.googleapis.com"
                  page = page_method
                  method = "DELETE"
                  header = "Authorization: Bearer " + self.getAccessToken()
              end with
              
              dim response as p = http_fetch(delete_settings)
              delete = response.body
          end function
      
          function test as l ()
              self.setAuthConfig("c:\data\**************.json")
              self.setScopes("https://www.googleapis.com/auth/admin.directory.user")
              self.setRedirectUri(getRedirectURIFromJson(7))
              self.setRegionNum(0)
              test = .t.
          end function
      
      end class
      google.login.a5w
      Code:
      <%a5
      
      'This page is used to grant new scopes to the regional oauth user
      
      'Load the class
      loadclass("apollo.google.auth.a5xbclass")
      'Then create the oauth2 url
      dim auth as apollo::google::auth
      auth.setAuthConfig("D:\data\**********.json")
      dim scopes[0] as c
      ' This scope is used to get the list of users in our company for the gen_territories subscribers dropdown
      scopes[] = "https://www.googleapis.com/auth/admin.directory.user.readonly"
      ' This scope is used to edit the groups in our company. Used for Franchise Mailing list
      scopes[] = "https://www.googleapis.com/auth/admin.directory.group"
      auth.setScopes(stritran(scopes.dump(),crlf()," "))
      auth.setRedirectUri(auth.getRedirectURIFromJson(7))
      'Override the region so it goes to my [email protected] account
      auth.setRegionNum(0)
      
      Context.Response.Redirect(auth.createAuthUrl())
      
      %>
      google.auth.a5w
      Code:
      <%a5 
      'This page is step two from the OAuth2 authentication
      
      'We've already loaded our settings, then created an OAuth2 URL.
      'The user has already gone to the OAuth2 URL and authenticated with Google
      'This is done in the google.login.a5w page
      'Then Google sends them to this page. It is this pages responsibility to use
      'auth code and exchange it for the Refresh Token. (Then save that refresh token)
      
      dim return as p    
      return.hasError = .f.
      return.errorText = ""
      
      'First, check to see if there is an error.
      if variable_exists("Context.Request.Variables.error") then
          return.hasError = .t.
          return.errorText = Context.Request.Variables.error
          ?json_generate(return)
          end
      end if
      
      dim auth as apollo::google::auth
      'Change the path to change google api projects
      if .not. auth.setAuthConfig("D:\data\**************.json") then
          return.hasError = .t.
          return.errorText = "Couldn't load secret JSON file"
          ?json_generate(return)
          end
      end if
      
      auth.setRedirectUri(auth.getRedirectURIFromJson(7))
      auth.setRegionNum(0)
      
      'Response should return access_token, expires_in, token_type, and refresh_token
      if .not. auth.fetchTokensWithAuthCode(Context.Request.Variables.code) then
          'Failure
          return.hasError = .t.
          return.errorText = "Couldn't exchange code for tokens"
          ?json_generate(return)
          'Otherwise the tokens were saved to the database!
      end if
      
      Context.Response.Redirect("")
      
      %>
      Then you can use auth.get/post() functions to call the google api.
      Last edited by Sparticuz; 08-09-2018, 01:13 PM. Reason: censor

      Comment


        #4
        Re: Oauth for Google API

        I don't use this word much but: this is Awesome. Thank you. I'm about to be out for a few days but may see if I can do this yet tonight. Thank you very much.
        -Steve
        sigpic

        Comment


          #5
          Re: Oauth for Google API

          hi .. i want to add that you must have SSL certificate to deal with google map ... i am sure that google have depreciated access to googlemap for http
          and only https can access it ...

          good luck steve ...


          and sparticuz ... thanks for sharing this code .. :)
          To live anywhere in the world today and be against equality because of race or color is like living in Alaska and being against snow.�

          - William Faulkner

          Comment

          Working...
          X