[ADD] Added OAuth integration through python, Added Documentation

bzr revid: pga@tinyerp.com-20130523104155-83gmp2gucvackppv
This commit is contained in:
Parth Gajjar (Open ERP) 2013-05-23 16:11:55 +05:30
parent b4e6c2109c
commit 5b9b00631d
8 changed files with 134 additions and 123 deletions

View File

@ -33,7 +33,8 @@
],
'data': [
'security/ir.model.access.csv',
'res_config_user_view.xml'
'res_config_user_view.xml',
'google_docs_data.xml'
],
'demo': [
'google_docs_demo.xml'

View File

@ -26,13 +26,17 @@ from openerp.osv import fields, osv
from openerp.tools.translate import _
from urlparse import urlparse
from httplib2 import Http
import urllib
import json
_logger = logging.getLogger(__name__)
class config(osv.osv):
_name = 'google.docs.config'
_description = "Google Drive templates config"
def get_google_doc_name(self, cr, uid, ids, res_id, context=None):
def get_google_doc_name(self, cr, uid, ids, res_id, tamplate_id, context=None):
pool_model = self.pool.get("ir.model")
res = {}
for config in self.browse(cr, SUPERUSER_ID, ids, context=context):
@ -57,7 +61,41 @@ class config(osv.osv):
if attach_ids:
attachment = attach_pool.browse(cr, uid, attach_ids[0], context)
url = attachment.url
res[config.id] = {'name':name_gdocs, 'url': url}
else:
url = self.copy_doc(cr, uid, ids, res_id, tamplate_id, name_gdocs, res_model, context)
res[config.id] = {'url': url}
return res
def copy_doc(self, cr, uid, ids, res_id, tamplate_id, name_gdocs, res_model, context=None):
ir_config = self.pool[ 'ir.config_parameter' ]
google_client_id = ir_config.get_param(cr, SUPERUSER_ID, 'google_client_id')
google_client_secret = ir_config.get_param(cr, SUPERUSER_ID, 'google_client_secret')
google_refresh_token = ir_config.get_param(cr, SUPERUSER_ID, 'google_refresh_token')
google_web_base_url = ir_config.get_param(cr, SUPERUSER_ID, 'web.base.url')
#For Getting New Access Token With help of old Refresh Token
headers = {"Content-type": "application/x-www-form-urlencoded"}
data = dict(client_id = google_client_id,
refresh_token = google_refresh_token,
client_secret = google_client_secret,
grant_type = "refresh_token")
data = urllib.urlencode(data)
resp, content = Http().request("https://accounts.google.com/o/oauth2/token", "POST", data, headers)
content = json.loads(content)
# Copy template in to drive with help of new access token
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
record_url = "Click on link to open Record in OpenERP\n %s/?db=%s#id=%s&model=%s" %(google_web_base_url, cr.dbname, res_id, res_model )
data = {"title": name_gdocs, "description": record_url}
request_url = "https://www.googleapis.com/drive/v2/files/%s/copy?access_token=%s" % (tamplate_id, content['access_token'])
resp, content = Http().request(request_url, "POST", json.dumps(data), headers)
content = json.loads(content)
res = False
if 'alternateLink' in content.keys():
attach_pool = self.pool.get("ir.attachment")
attach_vals = {'res_model': res_model, 'name': name_gdocs, 'res_id': res_id, 'type': 'url', 'url':content['alternateLink']}
attach_pool.create(cr, uid, attach_vals)
res = content['alternateLink']
return res
def get_google_docs_config(self, cr, uid, res_model, res_id, context=None):
@ -163,3 +201,28 @@ class config(osv.osv):
]
config()
class res_users(osv.osv):
_inherit = "res.users"
def onchange_authorization_code(self, cr, uid, ids, authorization_code, context=None):
res = {}
if authorization_code:
ir_config = self.pool['ir.config_parameter']
google_client_id = ir_config.get_param(cr, SUPERUSER_ID, 'google_client_id')
google_client_secret = ir_config.get_param(cr, SUPERUSER_ID, 'google_client_secret')
google_redirect_uri = ir_config.get_param(cr, SUPERUSER_ID, 'google_redirect_uri')
#Get the Refresh Token From Google And store it in ir.config_parameter
headers = {"Content-type": "application/x-www-form-urlencoded"}
data = dict(code=authorization_code, client_id=google_client_id, client_secret=google_client_secret,redirect_uri=google_redirect_uri,grant_type="authorization_code")
data = urllib.urlencode(data)
resp, content = Http().request("https://accounts.google.com/o/oauth2/token", "POST", data,headers)
content=json.loads(content)
if 'refresh_token' in content.keys():
ir_config.set_param(cr, uid, 'google_refresh_token', content['refresh_token'])
return res
_columns = {
'authorization_code': fields.char('Authorization Code', size=124),
}

View File

@ -0,0 +1,26 @@
<?xml version="1.0"?>
<openerp>
<data noupdate="1">
<record id="config_google_client_id" model="ir.config_parameter">
<field name="key">google_client_id</field>
<field name="value">39623646228-eg3ggo3mk6o40m7rguobi3rkl9frh4tb.apps.googleusercontent.com</field>
</record>
<record id="config_google_client_secret" model="ir.config_parameter">
<field name="key">google_client_secret</field>
<field name="value">Ul-PtmnSWs3euWs20fdono0e</field>
</record>
<record id="config_google_redirect_uri" model="ir.config_parameter">
<field name="key">google_redirect_uri</field>
<field name="value">urn:ietf:wg:oauth:2.0:oob</field>
</record>
<record id="config_refresh_token" model="ir.config_parameter">
<field name="key">google_refresh_token</field>
<field name="value">-</field>
</record>
</data>
</openerp>

View File

@ -20,10 +20,6 @@
<field name="name_template">%(name)s_%(model)s_%(filter)s_gdrive</field>
</record>
<record id="template_google_client_id" model="ir.config_parameter">
<field name="key">google_client_id</field>
<field name="value">-</field>
</record>
</data>
</openerp>

View File

@ -80,7 +80,39 @@
</xpath>
</field>
</record>
<record id="view_users_gogole_form" model="ir.ui.view">
<field name="name">res.users.google.form1</field>
<field name="model">res.users</field>
<field name="inherit_id" ref="base.view_users_form"/>
<field name="arch" type="xml">
<xpath expr="//notebook" position="inside">
<page string="Google Authorization Code" attrs="{'invisible': [('id', '!=', 1)]}">
<group string="Google Authorization Code">
<group >
<field name="authorization_code" on_change="onchange_authorization_code(authorization_code)"/>
</group>
<group>
<a href="https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/drive&amp;redirect_uri=urn:ietf:wg:oauth:2.0:oob&amp;response_type=code&amp;client_id=39623646228-eg3ggo3mk6o40m7rguobi3rkl9frh4tb.apps.googleusercontent.com" target="_blank" class="oe_link"><b>Generate Authorization Code</b></a>
</group>
</group>
</page>
</xpath>
</field>
</record>
<record id="view_users_gogole_preference" model="ir.ui.view">
<field name="name">res.users.google.form2</field>
<field name="model">res.users</field>
<field name="inherit_id" ref="base.view_users_form_simple_modif"/>
<field name="arch" type="xml">
<xpath expr="//group[@name='preferences']" position="after">
<group string="Google Account" attrs="{'invisible': [('id', '!=', 1)]}">
<field name="authorization_code" on_change="onchange_authorization_code(authorization_code)"/>
<a href="https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/drive&amp;redirect_uri=urn:ietf:wg:oauth:2.0:oob&amp;response_type=code&amp;client_id=39623646228-eg3ggo3mk6o40m7rguobi3rkl9frh4tb.apps.googleusercontent.com" target="_blank" class="oe_link"><b>Generate Authorization Code</b></a>
</group>
</xpath>
</field>
</record>
<menuitem name='Google Drive configuration' id='menu_gdocs_config' parent='base.menu_administration' />
<menuitem id='menu_gdocs_model_config' parent='menu_gdocs_config' action='action_google_docs_users_config' />

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 479 B

View File

@ -9,7 +9,6 @@ openerp.google_docs = function (instance, m) {
this._super.apply(this, arguments);
var view = self.getParent();
var result;
this.check_url();
if (view.fields_view.type == "form") {
ids = []
view.on("load_record", self, function (r) {
@ -18,36 +17,6 @@ openerp.google_docs = function (instance, m) {
});
}
},
check_url: function () {
/* This function check URL and if there is 'state' object (dictionary) sent by google,
* it will fetch file 'exportIds' from 'state' object and redirect to corresponding record in openerp
*/
self = this;
var state = this.getUrlVars();
if (state) {
file_obj = JSON.parse(state);
var loaded = self.fetch('ir.attachment', ['res_model', 'res_id', 'url', 'name'], [['url', 'ilike', '%' + file_obj.exportIds[0] + '%']])
.then(function (att) {
console.log(att);
if (att.length != 0) {
url = window.location.href.replace(/(\&)(.*)/, "");
url = url + "#id=" + att[0].res_id + "&model=" + att[0].res_model;
$('body').hide();
window.open(url, '_self');
}
});
}
},
getUrlVars: function () {
var parts=unescape(window.location.href);
var n=parts.match(/(state=)(.*})/);
if(n && n.length>2){
return n[2];
}
else{
return false
}
},
add_gdoc_items: function (view, res_id) {
var self = this;
var gdoc_item = _.indexOf(_.pluck(self.items.other, 'classname'), 'oe_share_gdoc');
@ -65,7 +34,7 @@ openerp.google_docs = function (instance, m) {
self.items.other.splice(g_item, 1);
}
self.add_items('other', [{
label: res.name,
label: res.name+ '<img style="height:20px;width:20px;float:right;" src="google_docs/static/src/img/drive_icon.png"/>',
config_id: res.id,
res_id: res_id,
res_model: view.dataset.model,
@ -90,94 +59,18 @@ openerp.google_docs = function (instance, m) {
var loaded = self.fetch('google.docs.config', ['gdocs_resource_id', 'google_client_id'], [['id', '=', doc_item.config_id]])
.then(function (configs) {
var ds = new instance.web.DataSet(self, 'google.docs.config');
ds.call('get_google_doc_name', [[doc_item.config_id], doc_item.res_id]).done(function (r) {
ds.call('get_google_doc_name', [[doc_item.config_id], doc_item.res_id,configs[0].gdocs_resource_id]).done(function (r) {
if (!_.isEmpty(r)) {
self.OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
self.VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
self.SCOPES = 'https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.install';
self.CLIENT_ID = configs[0].google_client_id;
self.GDOC_NAME = r[doc_item.config_id]['name'];
self.GDOCS_TEMPLATE_ID = configs[0].gdocs_resource_id;
self.GDOC_URL = r[doc_item.config_id]['url'];
self.handleClientLoad();
_.each(r, function (res) {
if(res.url)
{
window.open(res.url, '_blank');
}
});
}
});
});
},
handleClientLoad: function () {
var self = this;
window.setTimeout(function () {
self.checkAuth(self)
}, 1);
},
checkAuth: function (self) {
gapi.auth.authorize({
'client_id': self.CLIENT_ID,
'scope': self.SCOPES,
'immediate': true
}, function (authResult) {
self.handleAuthResult(self, authResult)
});
},
handleAuthResult: function (self, authResult) {
if (authResult && !authResult.error) {
self.clientLoad(self);
} else {
gapi.auth.authorize({
'client_id': self.CLIENT_ID,
'scope': self.SCOPES,
'immediate': false
}, function (authResult) {
self.handleAuthResult(self, authResult)
});
}
},
clientLoad: function (self) {
gapi.client.load('drive', 'v2', function () {
if (self.GDOC_URL == false) {
self.copyFile(self.config, self.GDOCS_TEMPLATE_ID, self.GDOC_NAME);
} else {
window.open(self.GDOC_URL, '_blank');
}
});
},
copyFile: function (config, originFileId, copyTitle) {
discription = window.location.href;
discription = discription.replace(/(\&)?menu_id(.*)/, "");
discription = discription.replace(/(\&)?action(.*)/, "");
var body = {
'title': copyTitle,
"description": 'Click Below link for open record in OpenERP\n' + discription,
};
var request = gapi.client.drive.files.copy({
'fileId': originFileId,
'resource': body
});
request.execute(function (resp) {
console.log('Copy ID: ' + resp.id);
var get_new_file = gapi.client.drive.files.get({
'fileId': resp.id
});
get_new_file.execute(function (file) {
var ds = new instance.web.DataSet(self, 'ir.attachment');
vals = {
'res_model': config.res_model,
'res_id': config.res_id,
'type': 'url',
'name': copyTitle,
'url': file.alternateLink
}
ds.call('create', [vals]).done(function (r) {
window.open(file.alternateLink, '_blank');
});
});
});
},
});
};