Django admin and MongoEngine ObjectID instead of int() - django-admin

Small test case is https://github.com/mekanix/djangomongodbtest, I can't seem to get admin page to show up. I login and get "int() argument must be a string or a number, not 'ObjectId'" exception. Is django admin used with mongoengine at all or do I have to use something like https://github.com/jschrewe/django-mongoadmin? Thanx!

You may need to update the handler for admin as well. The Django provided handler admin.site.urls does not work with Mongo.
from django.conf.urls import include
from django_mongoengine import mongo_admin
urlpatterns = [
url(r'^admin/', include(mongo_admin.site.urls)),
]

Related

Unautorized API calls JwtCreator

I'm playing around with the DocuSign's Ruby Quickstart app and I've done the following:
have an Admin account
have an organization
created an Integration(Connected App) for which I've granted signature impersonation scopes in the Admin Dashboard(made RSA keys, put callback urls, etc)
even if I've done the above, I've also made the request to the consent URL in a browser: SERVER/oauth/auth?response_type=code &scope=signature%20impersonation&client_id=CLIENT_ID &redirect_uri=REDIRECT_URI
Integration appears to have everything enabled
Then in the JwtCreator class the check_jwt_token returns true, updates account info correctly.
But when I try the following(or any other API call):
envelope_api = create_envelope_api(#args)
options = DocuSign_eSign::ListStatusChangesOptions.new
options.from_date = (Date.today - 30).strftime('%Y/%m/%d')
results = envelope_api.list_status_changes #args[:account_id], options
The api call raises an exception with DocuSign_eSign::ApiError (Unauthorized):
Args are:
#args = {
account_id: session[:ds_account_id],
base_path: session[:ds_base_path],
access_token: session[:ds_access_token]
}
All with correct info.
What am I missing?
For clarity, I was using some classes from the Quickstart app(like JwtCreator, ApiCreator, etc) along my code.
Not sure at this point if it's my mistake or part of the Quickstart app but this call:
results = envelope_api.list_status_changes #args[:account_id], options
the account_id was something like this "82xxxx-xxxx-xxxx-xxxx-xxxxxxxx95e" and I was always getting Unauthorized responses.
On a medium.com tutorial the author used the 1xxxxxx account_id and with this form, it worked.

Manually Invoking email verification

We've been using django-allauth for quite some time now in production. We can enable account email verification which works great. But we now have a REST api that allows users to register through the API and the workflow doesn't go through django-allauth. Is it possible to manually invoke the django-allauth email verification feature or do we need to use a custom solution?
I'll just post my answer here as I've been searching for adding email verification with Django Built-in Authentication (And using a Custom Auth Model), I used the method mentioned by Marcus, I'll just add all the other stuff around it for anyone who wants to do the same.
First: Install django-allauth as described here
Second: Add your email configurations in the settings.py file :
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com' #I used gmail in my case
EMAIL_HOST_USER = <Your Email>
EMAIL_HOST_PASSWORD = <Your Password>
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = <Default Sender name and email>
Third: Add configurations for verification and default login url, you'll find the documentation of all config parameters here, note that in my example I'm using a custom user model as mentioned, that's why I'm setting ACCOUNT_EMAIL_REQUIRED to True & ACCOUNT_USER_MODEL_USERNAME_FIELD and ACCOUNT_USERNAME_REQUIRED to False, also the LOGIN_URL,ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL andLOGIN_REDIRECT_URL parameters are used after the user clicks on the confirmation link sent by email to him
ACCOUNT_EMAIL_VERIFICATION='mandatory'
ACCOUNT_CONFIRM_EMAIL_ON_GET=True
ACCOUNT_EMAIL_REQUIRED=True
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
LOGIN_URL='app:login_user'
LOGIN_REDIRECT_URL='app:login_user'
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL='app:login_user'
Fourth: After your signup form, save the user instance with is_active parameter set to False, then call the method:
from allauth.account.utils import *
send_email_confirmation(request, user, True)
Finally: Receive the signal after the user confirms his email, and set is_active to True
from allauth.account.signals import email_confirmed
from django.dispatch import receiver
# Signal sent to activate user upon confirmation
#receiver(email_confirmed)
def email_confirmed_(request, email_address, **kwargs):
user = MyUser.objects.get(email=email_address.email)
user.is_active = True
user.save()
Finally, you would want to change the default site name from Django Admin as it will be included in the email sent.
I had the same problem, and the solution I've found was to call the original send_email_confirmation method from allauth. I am using DRF3 for my API.
from allauth.account.utils import send_email_confirmation
...
def some_view(request):
user = ...
...
#using request._request to avoid TypeError on change made in DRF3 (from HTTPRequest to Request object)
send_email_confirmation(request._request, user)
...
I hope this helps you.

Configure multiple login sessions using google oauth

I am using Google OAuth for Google signin with Odoo.
Everything works fine and I can sign in using google with no problem. However, I cannot open multiple sessions using my same google credentials.
For example, if I open two sessions, one in chrome and another in firefox, then the older session gets logged out.
I don't understand what's the problem because no matter how many sessions I start if I log in using my username and password separately, without using google OAuth, none of the sessions get logged out - works fine.
I was wondering it has got something to do with the code, so I did a lot of tweaks but nothing works. I saw that at one point it cannot get the session information of older sessions. However my question is not about the code.
My question is, is there any configuration or setting to be set in google OAuth or Odoo 8 which lets users have multiple sessions at the same time or is there any setting while using google OAuth with Odoo that I need to know for this?
Any idea would be really helpful as I've been struggling for days with this. Thanks!
I have build a module for Odoo V9. Without this module, Odoo save only one token. But when you use odoo in multi computer, you use one token for each computer.
By default odoo don't support multi token. You need to modify the code of module auth_oauth.
With this module it save all token, like that you can have multi connection.
You can donwload and instal this module : https://github.com/IguanaYachts/auth_oauth_multi_token.git
class ResUsers(models.Model):
_inherit = 'res.users'
oauth_access_token_ids = fields.One2many('auth.oauth.multi.token', 'user_id', 'Tokens', copy=False)
oauth_access_max_token = fields.Integer('Number of simultaneous connections', default=5, required=True)
#api.model
def _auth_oauth_signin(self, provider, validation, params):
res = super(ResUsers, self)._auth_oauth_signin(provider, validation, params)
oauth_uid = validation['user_id']
user_ids = self.search([('oauth_uid', '=', oauth_uid), ('oauth_provider_id', '=', provider)]).ids
if not user_ids:
raise openerp.exceptions.AccessDenied()
assert len(user_ids) == 1
self.oauth_access_token_ids.create({'user_id': user_ids[0],
'oauth_access_token': params['access_token'],
'active_token': True,
})
return res
#api.multi
def clear_token(self):
for users in self:
for token in users.oauth_access_token_ids:
token.write({
'oauth_access_token': "****************************",
'active_token': False})
#api.model
def check_credentials(self, password):
try:
return super(ResUsers, self).check_credentials(password)
except openerp.exceptions.AccessDenied:
res = self.env['auth.oauth.multi.token'].sudo().search([
('user_id', '=', self.env.uid),
('oauth_access_token', '=', password),
('active_token', '=', True),
])
if not res:
raise
If you follow the steps above you will be able to successfully configure Google Apps (Gmail) with OpenERP via the OAuth module. The only thing i was missing is an extra step I found in a youtube video; you have to:
Go to Settings - Users
To the users you want to give OAuth access, send them a password reset by using the "Send reset password instructions by email" option.
Ask your users (or yourself) to use the link they receive in their email, but, when they open it, they will only see the log in screen with the "Log in with Google" option. (no typical change password option available)
Use the proper Google account and voila! - Now it connects smoothly.
The Youtube video that show how to log in with Google in OpenERP: http://www.youtube.com/watch?v=A-iwzxEeJmc
and if configuration of Oauth2 and odoo see this link for more detail
https://odootricks.wordpress.com/2014/09/18/setting-up-google-apps-authentication-for-odoo/

I can't seem to get the first Twitter4J code example (Simple post on Twitter) to work. UpdateStatus(string) is undefined

So this is my problem right now:
I went to http://twitter4j.org/en/code-examples.html as I just started to use twitter4j (version 4.0.2 as far as I can remember) and I wanted to try to code examples to get a basic understanding of T4J.
However, it seems like I can't even get the first example to work. This is my code right now:
import twitter4j.Status;
import twitter4j.TwitterFactory;
public class Twitter {
public static void main(String[] args) {
String latestStatus="Test";
Twitter twitter = (Twitter) TwitterFactory.getSingleton();
Status status = twitter.updateStatus(latestStatus);
System.out.println("Successfully updated the status to [" + status.getText() + "].");
}
}
This is exactly to code I found on code examples (Plus the string which should end up being the status). However, I always get an error at Status status=twitter.updateStatus(latestStatus), which is basically this:
The method updateStatus(String) is undefined for the type Twitter
I have literally no idea what could be wrong here. I mean in the end it's the official code example. Even the official doc is using strings as parameter for that method.
Can anyone give me a helping hand?
Thanks in advance.
You need couple of things to make this code work -
First you need to register your app with Twitter and generate OAuth Authentication. You will get following - consumerkey, consumersecret, accesstoken and accesstokensecret.
Using the keys and secret you would create a Twitter instance, which you can use to access your Twitter User ID.
Second you need to authorize your app to be able to write updates default permission is Read Only.
You can register and manage your app at https://apps.twitter.com/
Also about the twitter$j library version, please use a latest one.
Here is a code snippet to use the authentication keys and update the status -
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("consumerKey")
.setOAuthConsumerSecret("consumerSecret")
.setOAuthAccessToken("accessToken")
.setOAuthAccessTokenSecret("accessTokenSecret");
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
Status status = twitter.updateStatus("test");
Hope this is helpful.
This is happening because your class is called Twitter, so
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
will be interpreted as you trying to create an instance of your class Twitter, rather than an instance of twitter4j.Twitter. You could change the name of your class to something else, or change the library Twitter instances to twitter4j.Twitter instances to specify the difference.

Twitter O-Auth Callback url

I am having a problem with Twitter's oauth authentication and using a callback url.
I am coding in php and using the sample code referenced by the twitter wiki, http://github.com/abraham/twitteroauth
I got that code, and tried a simple test and it worked nicely. However I want to programatically specify the callback url, and the example did not support that.
So I quickly modified the getRequestToken() method to take in a parameter and now it looks like this:
function getRequestToken($params = array()) {
$r = $this->oAuthRequest($this->requestTokenURL(), $params);
$token = $this->oAuthParseResponse($r);
$this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
return $token;
}
and my call looks like this
$tok = $to->getRequestToken(array('oauth_callback' => 'http://127.0.0.1/twitter_prompt/index.php'));
This is the only change I made, and the redirect works like a charm, however I am getting an error when I then try and use my newly granted access to try and make a call. I get a "Could not authenticate you" error. Also the application never actually gets added to the users authorized connections.
Now I read the specs and I thought all I had to do was specify the parameter when getting the request token. Could someone a little more seasoned in oauth and twitter possibly give me a hand? Thank You
I think this is fixed by twitter by now or you might have missed to provide a default callback url in your application settings, which is required for dynamic callback url to work as mentioned by others above.
Any case, I got this working by passing the oath_callback parameter while retrieving the request token. I am using twitter-async PHP library and had to make a small tweak to make the library pass the callback url.
If you are using twitter-async, the change is below:
modified getRequestToken and getAuthenticateURL functions to take callback url as parameter
public function getRequestToken($callback_url = null)
{
$params = empty($callback_url) ? null : array('oauth_callback'=>$callback_url);
$resp = $this->httpRequest('GET', $this->requestTokenUrl, $params);
return new EpiOAuthResponse($resp);
}
public function getAuthenticateUrl($callback_url = null)
{
$token = $this->getRequestToken($callback_url);
return $this->authenticateUrl . '?oauth_token=' . $token->oauth_token;
}
And pass the callback url from your PHP code.
$twitterObj->getAuthenticateUrl('http://localhost/twitter/confirm.php');
#Ian, twitter now allows 127.0.0.1 and has made some other recent changes.
#jtymann, check my answer here and see if it helps
Twitter oauth_callback parameter being ignored!
GL
jingles
even me to was getting 401 error.. but its resolved..
during registering your application to twitter you need to give callback url...
like http://localhost:8080.
i have done this using java...
so my code is: String CallbackURL="http://localhost:8080/tweetproj/index.jsp";
provider.retrieveRequestToken(consumer,CallbackURL);
where tweetproj is my project name
and index.jsp is just one jsp page...
Hope this may helps u...
After the user authorizes the application on twitter.com and they return to your callback URL you have to exchange the request token for an access token.
Twitter does not honor the oauth_callback parameter and will only use the one specified in the registered application settings.
It also doesn't allow for 127.0.0.1 or localhost names in that callback, so I've setup http://dev.twipler.com which is setup for 127.0.0.1 in DNS so you can safely use;
http://dev.twipler.com/twitter_prompt/index.php

Resources