views.py
from tutorial.graph_helper import *
from django.urls import reverse
from tutorial.auth_helper import get_sign_in_url, get_token_from_code, store_token, store_user, remove_user_and_token, get_token
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
import dateutil.parser
def home(request):
context = initialize_context(request)
return render(request, 'tutorial/home.html', context)
def userslist(request):
context = initialize_context(request)
token = get_token(request)
usersdata = get_users(token)
if usersdata :
#for user in usersdata['value']
print ('users fetched')
print (usersdata)
else:
print('no output')
print('yeta ka')
context['usersdata'] = usersdata['value']
return render(request, 'tutorial/userslist.html',context)
def groupslist(request):
context = initialize_context(request)
token = get_token(request)
groupsdata = get_groups(token)
if groupsdata :
#for group in groupsdata['value']
print ('groups fetched')
print (groupsdata)
else:
print('no output')
print('yeta ka')
context['groupsdata'] = groupsdata['value']
return render(request, 'tutorial/groupslist.html',context)
def newuserindex(request):
return render(request, 'createsingleuser.html')
def createsingleuser(request):
context = initialize_context(request)
token = get_token(request)
if request.method =='POST':
context = request.POST
context1 = {
"accountEnabled": 'true',
"city": context['city'],
"country": context['country'],
"department": context['department'],
"displayName": context['displayName'],
"givenName": context['givenName'],
"jobTitle": context['jobTitle'],
"mailNickname": context['mailNickname'],
"passwordPolicies": "DisablePasswordExpiration",
"passwordProfile": {
"password": "Test1234",
"forceChangePasswordNextSignIn": 'false'
},
"officeLocation": context['officeLocation'],
"postalCode": context['postalCode'],
"preferredLanguage": context['preferredLanguage'],
"state": context['state'],
"streetAddress": context['streetAddress'],
"surname": context['surname'],
"mobilePhone": context['mobilePhone'],
"usageLocation": context['mobilePhone'],
"userPrincipalName": context['userPrincipalName']
}
newuser = create_user(token,context1)
print (newuser)
return render(request, 'tutorial/createsingleuser.html', context)
def initialize_context(request):
context = {}
# Check for any errors in the session
error = request.session.pop('flash_error', None)
if error != None:
context['errors'] = []
context['errors'].append(error)
# Check for user in the session
context['user'] = request.session.get('user', {'is_authenticated': False})
return context
def sign_in(request):
# Get the sign-in URL
sign_in_url, state = get_sign_in_url()
# Save the expected state so we can validate in the callback
request.session['auth_state'] = state
# Redirect to the Azure sign-in page
return HttpResponseRedirect(sign_in_url)
def callback(request):
# Get the state saved in session
expected_state = request.session.pop('auth_state', '')
# Make the token request
token = get_token_from_code(request.get_full_path(), expected_state)
# Get the user's profile
user = get_user(token)
# Save token and user
store_token(request, token)
store_user(request, user)
return HttpResponseRedirect(reverse('home'))
def sign_out(request):
# Clear out the user and token
remove_user_and_token(request)
return HttpResponseRedirect(reverse('home'))
def calendar(request):
context = initialize_context(request)
token = get_token(request)
events = get_calendar_events(token)
if events:
# Convert the ISO 8601 date times to a datetime object
# This allows the Django template to format the value nicely
for event in events['value']:
event['start']['dateTime'] = dateutil.parser.parse(event['start']['dateTime'])
event['end']['dateTime'] = dateutil.parser.parse(event['end']['dateTime'])
context['events'] = events['value']
return render(request, 'tutorial/calendar.html', context)
graph_helper.py
from requests_oauthlib import OAuth2Session
import json
import requests
graph_url = 'https://graph.microsoft.com/v1.0'
def get_user(token):
graph_client = OAuth2Session(token=token)
# Send GET to /me
user = graph_client.get('{0}/me'.format(graph_url))
# Return the JSON result
return user.json()
def get_calendar_events(token):
graph_client = OAuth2Session(token=token)
# Configure query parameters to
# modify the results
query_params = {
'$select': 'subject,organizer,start,end',
'$orderby': 'createdDateTime DESC'
}
# Send GET to /me/events
events = graph_client.get('{0}/me/events'.format(graph_url), params=query_params)
# Return the JSON result
return events.json()
def get_users(token):
graph_client = OAuth2Session(token=token)
# Send GET to /users
users = graph_client.get('{0}/users'.format(graph_url))
# Return the JSON result
return users.json()
def get_groups(token):
graph_client = OAuth2Session(token=token)
# Send GET to /groups
groups = graph_client.get('{0}/groups'.format(graph_url))
# Return the JSON result
return groups.json()
def create_user(token, context1):
graph_client = OAuth2Session(token=token)
headers = { 'Authorization' : 'Bearer {0}'.format(token),
'Accept' : 'application/json',
'Content-Type' : 'application/json' }
# newuser = graph_client.post('https://graph.microsoft.com/v1.0/users', headers = {"Content-Type":"application/json", data=context1, })
newuser = graph_client.post('{0}/users'.format(graph_url), headers = headers, json = context1)
return newuser