Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SOCIALAUTH]: Update and Refactor #710

Merged
merged 1 commit into from Jan 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
68 changes: 64 additions & 4 deletions jaseci_serv/jaseci_serv/jsx_oauth/HOWTO.md
@@ -1,10 +1,70 @@
# **`GITHUB`**
# **`ADD SOCIALAPP`**

- [GitHub Documentation](https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps) for Authorizing OAuth Apps
- Add Social App for GitHub in Admin Panel
![Add GitHub on SocialApp](https://user-images.githubusercontent.com/74129725/209335723-283fc800-78bd-47af-82e5-895720d8f382.png)
- Add GlobalVars for `GITHUB_REDIRECT_URI`
![GITHUB_REDIRECT_URI](https://user-images.githubusercontent.com/74129725/209336232-67c6918c-da37-4632-96cb-551b76f267ca.png)

---

# **`GETTING TOKEN (USING AUTHORIZATION CODE)`**
### **METHOD**:
POST
### **URL**:
**/auth/`{{provider}}`**
> ex: /auth/google

### **BODY**:
```js
{
id_token: "",
code: "{{authorization code}}",
access_token: "",
// optional: used if FE wants to redirect it to different url
callback_url: redirect_uri
}
```

---

# **`GOOGLE`**

- [Google Documentation](https://developers.google.com/identity/protocols/oauth2/web-server#python) for Authorizing OAuth Apps
- [Add SocialApp](./HOWTO.md) for Google
- Use the sample code from Google docs for getting Authorization code
```js
<button onclick="client.requestCode();">Login with Google</button>

<script src="all required scripts from docs"></script>
<script>
const client = google.accounts.oauth2.initCodeClient({
client_id: "{{client_id}}",
scope: "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile openid",
ux_mode: 'redirect',
redirect_uri: "http://localhost:8001/auth/examples/" + provider + "/",
state: "offline"
});
</script>
```
- Upon successful login authorization code should now be present on URL and can be used on [getting Access Token](./HOWTO.md)
- Try it on your local using `/auth/examples/google/`

---
# **`GITHUB`**

- [GitHub Documentation](https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps) for Authorizing OAuth Apps
- [Add SocialApp](./HOWTO.md) for GitHub
- you need to redirect to this URL format
> https://github.com/login/oauth/authorize?client_id=`{{your GitHub OAuth App's client ID}}`&redirect_uri=`{{your GitHub OAuth App's allowed callback URI set in GitHub OAuth App}}`&scope=read:user,user:email&state=`{{your any random str}}`
- Upon successful login authorization code should now be present on URL and can be used on [getting Access Token](./HOWTO.md)
- Try it on your local using `/auth/examples/github/`

---
# **`FACEBOOK`**

- [Facebook Documentation](https://developers.facebook.com/docs/facebook-login/guides/advanced/manual-flow#checklogin) for Authorizing OAuth Apps
- [Add SocialApp](./HOWTO.md) for Facebook
- you need to redirect to this URL format
>https://github.com/login/oauth/authorize?client_id=`{{your GitHub OAuth App's client ID}}`&redirect_uri=`{{your GitHub OAuth App's allowed callback URI set in GitHub OAuth App}}`&scope=read:user,user:email&state=`{{your any random str}}`
- Try it on your local using `/auth/examples/github/`
> https://www.facebook.com/dialog/oauth/?client_id=`{{your Facebook OAuth App's client ID}}`&redirect_uri=`{{your Facebook OAuth App's allowed callback URI set in Facebook OAuth App}}`&scope=email&state=`{{your any random str}}`
- Upon successful login authorization code should now be present on URL and can be used on [getting Access Token](./HOWTO.md)
- Try it on your local using `/auth/examples/facebook/`
10 changes: 0 additions & 10 deletions jaseci_serv/jaseci_serv/jsx_oauth/config.py
Expand Up @@ -19,16 +19,6 @@

AUTH_PROVIDERS = {"facebook": "facebook", "google": "google", "email": "email"}

SOCIAL_AUTH_CREDS = {
"google": {
"GOOGLE_CLIENT_ID": os.environ.get("GOOGLE_CLIENT_ID"),
"GOOGLE_CLIENT_SECRET": os.environ.get("GOOGLE_CLIENT_SECRET"),
},
"facebook": {
"FACEBOOK_CLIENT_ID": os.environ.get("FACEBOOK_CLIENT_ID"),
"FACEBOOK_CLIENT_SECRET": os.environ.get("FACEBOOK_CLIENT_SECRET"),
},
}

KNOX_TOKEN_EXPIRY = 24

Expand Down
8 changes: 7 additions & 1 deletion jaseci_serv/jaseci_serv/jsx_oauth/models.py
Expand Up @@ -18,26 +18,32 @@ class SocialLoginProvider(models.TextChoices):
SocialLoginProvider.GOOGLE: {
"URL_KEY": SocialLoginProvider.GOOGLE + "_REDIRECT_URI",
"LOGIN_URL": "https://accounts.google.com/o/oauth2/v2/auth?redirect_uri={callback_url}&prompt=consent&response_type=code&client_id={client_id}&scope=openid%20email%20profile&access_type=offline",
"DEFAULT_REDIRECT_URI": "/auth/examples/google/",
},
SocialLoginProvider.FACEBOOK: {
"URL_KEY": SocialLoginProvider.FACEBOOK + "_REDIRECT_URI",
"LOGIN_URL": "https://www.facebook.com/v14.0/dialog/oauth?client_id={client_id}&redirect_uri={callback_url}&state={{st=state123abc,ds=123456789}}",
"LOGIN_URL": "https://www.facebook.com/v15.0/dialog/oauth?client_id={client_id}&redirect_uri={callback_url}&state={{st=state123abc,ds=123456789}}",
"DEFAULT_REDIRECT_URI": "/auth/examples/facebook/",
},
SocialLoginProvider.GITHUB: {
"URL_KEY": SocialLoginProvider.GITHUB + "_REDIRECT_URI",
"LOGIN_URL": "",
"DEFAULT_REDIRECT_URI": "/auth/examples/github/",
},
SocialLoginProvider.MICROSOFT: {
"URL_KEY": SocialLoginProvider.MICROSOFT + "_REDIRECT_URI",
"LOGIN_URL": "",
"DEFAULT_REDIRECT_URI": "/auth/examples/microsoft/",
},
SocialLoginProvider.OKTA: {
"URL_KEY": SocialLoginProvider.OKTA + "_REDIRECT_URI",
"LOGIN_URL": "",
"DEFAULT_REDIRECT_URI": "/auth/examples/okta/",
},
SocialLoginProvider.OPENID: {
"URL_KEY": SocialLoginProvider.OPENID + "_REDIRECT_URI",
"LOGIN_URL": "",
"DEFAULT_REDIRECT_URI": "/auth/examples/openid/",
},
}

Expand Down
33 changes: 14 additions & 19 deletions jaseci_serv/jaseci_serv/jsx_oauth/utils.py
@@ -1,10 +1,10 @@
from jaseci_serv.jsx_oauth.models import PROVIDERS_MAPPING
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from allauth.account.adapter import get_adapter
from dj_rest_auth.registration.views import SocialLoginView
from dj_rest_auth.registration.serializers import SocialLoginSerializer
from jaseci_serv.base.models import lookup_global_config
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from knox.settings import knox_settings
from knox.models import AuthToken
from django.contrib.auth import authenticate, get_user_model
Expand Down Expand Up @@ -87,8 +87,7 @@ def validate(self, attrs):
login = self.get_social_login(adapter, app, social_token, token)
complete_social_login(request, login)
except HTTPError:
raise serializers.ValidationError("Incorrect value")

raise serializers.ValidationError(_("Incorrect value"))
if not login.is_existing:
if allauth_settings.UNIQUE_EMAIL:
# Do we have an account already with this email address?
Expand Down Expand Up @@ -119,19 +118,25 @@ class JSXSocialLoginView(SocialLoginView):
serializer_class = JSXSocialLoginSerializer
# permission_classes = [IsValidateLicense, AllowAny]

def get_callback_url(self):
def get_callback_url(self, request):
callback_url = request.POST.get("callback_url")
if callback_url:
return callback_url

if self.provider:
return resolve(
PROVIDERS_MAPPING[self.provider]["URL_KEY"], request=self.request
prov = PROVIDERS_MAPPING[self.provider]
return lookup_global_config(
name=prov["URL_KEY"],
default=f'{request.build_absolute_uri("/")[:-1]}{prov["DEFAULT_REDIRECT_URI"]}',
)
raise RuntimeError(
"Provider name cannot be empty or None. "
'Please provide a valid provider name e.g. "GOOGLE"'
)

def dispatch(self, *args, **kwargs):
self.callback_url = self.get_callback_url()
return super().dispatch(*args, **kwargs)
def dispatch(self, request, *args, **kwargs):
self.callback_url = self.get_callback_url(request)
return super().dispatch(request, *args, **kwargs)

def post(self, request, *args, **kwargs):
self.request = request
Expand Down Expand Up @@ -162,13 +167,3 @@ def post(self, request, *args, **kwargs):
"exp": instance.expiry,
}
)


def resolve(name, request):
try:
value = lookup_global_config(name=name)
if not value and request:
value = f"{request.build_absolute_uri('/')[:-1]}{settings.DEFAULT_CALLBACK_URL_FOR_SSO}"
return value
except Exception as e:
return None
25 changes: 17 additions & 8 deletions jaseci_serv/templates/examples/social_auth.html
Expand Up @@ -53,6 +53,12 @@ <h1>Google Identity Services Authorization Token model</h1>
<i class="fa fa-github"></i> Sign in with Github
</a>
</div>
{% elif provider == "facebook" %}
<div class="col-md-3">
<a href="https://www.facebook.com/dialog/oauth/?client_id=3201469443497528&redirect_uri=http%3A%2F%2Flocalhost%3A8001%2Fauth%2Fexamples%2Ffacebook%2F&scope=email&state={{state}}" class="btn btn-block btn-social btn-facebook" style="text-align:center">
<i class="fa fa-facebook"></i> Continue with Facebook
</a>
</div>
{% endif %}
</div>
{% endif %}
Expand Down Expand Up @@ -100,7 +106,7 @@ <h1>Google Identity Services Authorization Token model</h1>
id_token: "",
code: "{{code}}",
access_token: "",
redirect_uri
callback_url: redirect_uri
},
success: (res) => {
console.log("response:", res);
Expand All @@ -113,12 +119,15 @@ <h1>Google Identity Services Authorization Token model</h1>
}
});
{% else %}
const client = google.accounts.oauth2.initCodeClient({
client_id: "{{client_id}}",
scope: "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile openid",
ux_mode: 'redirect',
redirect_uri: "http://localhost:8001/auth/examples/" + provider + "/",
state: "offline"
});
{% if provider == "google" %}

const client = google.accounts.oauth2.initCodeClient({
client_id: "{{client_id}}",
scope: "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile openid",
ux_mode: 'redirect',
redirect_uri: "http://localhost:8001/auth/examples/" + provider + "/",
state: "offline"
});
{% endif %}
{% endif %}
</script>