Playframework(Scala): passing user model around - scala

I wonder what's the best practise for passing user 'model' around. I take http request and convert it to user model in my controller. I don't want to explicitly add an argument to all the templates for this model, and neither to main.
What are the best practises for doing this?
THanks.

If you are logging in, and the user is your authenticated user, then you should put the user in a WrappedRequest and make your request implicit in your templates. If you use something like SecureSocial, then UserAwareAction will provide you with a RequestWithUser (see http://securesocial.ws/guide/user-service.html) and you can do things like
#()(implicit req:RequestWithUser)
Email = #{req.user.map(_.email)}
in your template.

Use the Session scope.
Here is documentation for Play 2.0
http://www.playframework.com/documentation/2.0.2/ScalaSessionFlash
So for example, on the login, add the user to the Session
And on logout remove the user from the Session
Cheers!

Related

How to override login of flask-security?

I want to do some customization when a user logs in. The problem is that the project is using flask-security which implicitly handles user login.
I want to check some records of users in the database when users log in.
How can I override "login" function in flask-security?
I saw a similar post, and tried it but it's not working.
Plus, it is not exactly what I want to do.
I maybe need to stop the default behavior in case of some users.
So, is anyone having this kind of issue? How can I do it?
You can override the login form when you are setting up Flask-Security:
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore, login_form=CustomLoginForm)
Then create your custom login form class that extends the default LoginForm. And override the validate function to do stuff before or after the login attempt.
from flask_security.forms import LoginForm
class CustomLoginForm(LoginForm):
def validate(self):
# Put code here if you want to do stuff before login attempt
response = super(CustomLoginForm, self).validate()
# Put code here if you want to do stuff after login attempt
return response
"reponse" will be True or False based on if the login was successful or not. If you want to check possible errors that occurred during the login attempt see "self.errors"
Greetings,
Kevin ;)
after registering the flask security extension, you can create an endpoint with the exact same name/route and it should override the one registered by Flask-security.
If you are using blueprints, make sure you register your blueprint before registering Flask-security.

Grails: calling an action that uses withForm

I have a situation in which I need to reuse an action that has its functionality wrapped in a withForm closure.
Everything works well when submitting the form but when I try to reuse that action in another way I get redirect errors from my browser. Specifically, I need to redirect another action to it, possibly call it with chain, and I also want to call it from a hyperlink.
I'd really like to avoid creating a redundant action or having the invalidToken closure execute the same code. I've tried to find some more details about how withForm works and find out what happens if no token is passed to the closure but the Googles have let me down.
Is this possible? Am I trying to make it do something it can't?
More info:
I have a user edit controller action. It is wrapped with the withForm closure. There are three different cases in which I need to call this controller to render the user edit page:
An admin enters the user's id into an input and clicks the form
submit button (this form uses useToken). This needs to be secured
and protected from duplicate form submission.
An admin selects a user to edit from a list of employees by clicking
on the user's name (a hyperlink). Its possible I could turn this into a form submission with useToken and do some CSS styling to make it look like a link.
An admin creates a new user. When the user is successfully created
the create controller redirects (or uses chain) to the edit
controller. I can't find a work around for this, except to create a redundant controller.
If your code is used in more than one place a controller action isn't the best place to put it. I suggest you to move that piece of code to a service and call it from both actions.
Here is my solution. If anyone has some insight into other methods of solving this please contribute. I'm sure I'm not the only one that has had this problem.
The answer is due, in large part to #Sergio's response. It was far more simple than what I was thinking it would be. I created my edit action without withFormthen call it from another action that wraps the edit action in the withForm.
def editWT(Long uid, Long pid){
withForm{
edit(uid, pid)
}
}
def edit(Long uid, Long pid){
// Do lots of stuff to prep the data for rendering the view
}
This answer isn't innovative or ground-breaking but it works. I hope this helps someone else.

What is an appropriate URI for a user registration form in a RESTful setting?

I'm working on a web application under Laravel and I'm trying to be as RESTful as I can, but admittedly this is the first time writing this kind of application.
I'm specifically trying to create RESTful URI's for the controllers of my project.
So far I have (in pseudo code)...
URI Goes to... Desc
--- ---------- ----
/ GET
if logged in dashboard GET
else frontpage GET
login GET login GET login form
login POST login POST attempt login
login DELETE login DELETE logout
user GET
if logged in user GET show user control panel
else login GET redirect to the login w/ error
So far so good, but how should I go about creating a new user?
I had a couple of ideas, for example:
URI Goes to... Desc
--- ---------- ----
user/create GET register GET show the create user form
user/create POST register POST attempt to create a new user
So we use a register controller here, but we hide it behind the user URI.
Advantage here is that we stick to HTTP actions (just GET and POST), and we create a nice readable URI.
Disadvantage is that our URI does not accurately represent our controller.
URI Goes to... Desc
--- ---------- ----
register GET register GET show the create user form
register POST register POST attempt to create a new user
In this case we have A. used HTTP controls, B. created a URI that is a representation of our controller, and C. created a nice readable URI, but unfortunately our URI isn't really representational of the data. In no way is this register controller representative of our user.
Which is more appropriate? Why? Is there a better way? Thanks!
In those cases I would create a Route::resource for users, like so:
Route::resource('user', 'UsersController');
and to optimize user readability add:
Route::get('/signup', 'UsersController#create');
For logins I would create a Route::resource for sessions, like so:
Route::resource('sessions', 'SessionsController');
and to again, optimize user readability add:
Route::get('/login', 'SessionsController#create');
Using resources makes some methods ready for you, but you are not using all of them.
So you might want to reduce that to the ones you use, only. Like so:
Route::resource('sessions', 'SessionsController', ['only' => ['create', 'store', 'destroy']);
Hope this helps you further.
In your case I will go for the user readability. I always prefer to have something like example.com/signup, example.com/register to show the form that handles the creation of the user. As a user, the URL tells me that I'm in the right place, even if the controller that handles this is totally different. The middle URL (where you will post your data) is not important because it will not displayed to your users: you will redirect them to the create form or the success page.
If you were building an API (the intended users are developers) I will go for a POST users, because developers should be familiar with REST principles.

How to have users 'reconnect' with soundcloud on each page reload?

I'm using the Javascript SDK inside a node.js (Express) App.
Connecting Users works fine, but the connection does not persist between page reloads.
Is this the default behaviour, or is the User supposed to stay connected in new requests?
Do I have to use OAuth token authentication and if so, how can this be done with the JS-SDK?
Inside the "Permission"-Popup, Users are already logged in with soundlcoud, though.
(just have to click the "connect" button each time)
Figured I'd share my answer for those who are unsatisfied with the current answers for automated oauth:
Retrieving access_token:
I had to define get and set cookie functions and then I use the functions to set and retrieve a function holding the access token. I'm not going to give these functions for conciseness but you can easily find them with a google search. I then use this line of code to get the SC access token (once the user has authenticated for the first time)
SC.accessToken()
Setting token:
So this is kind of just an elephant in the room in my opinion that for some reason no one has mentioned. How in the **** do you connect w/ SC using the access token? Do you set it as oauth param? On each call pass it? Well, after experimenting with putting the parameter in every single place I could think, I found out you have to do something like this:
SC.initialize({
client_id: '[removed for security reasons]',
client_secret: '[removed for security reasons]',
redirect_uri: '[removed for security reasons]',
access_token: getCookie("sc_lm2"),
scope: 'non-expiring'
});
//Where "sc_lm2" is the name of my cookie
Hope the helps! Took me a while to figure this out for such a simple thing
EDIT
Using PHP and Wordpress:
$json = wp_remote_get("http://api.soundcloud.com/users/[user_id]/tracks.json?client_id=[client_id]");
$soundcloudData = json_decode($json['body'],true);
(substitue cURL functionality if you're not using Wordpress). #krafty I assume you would just change the endpoint from "/tracks" to "/users" but I can't say I have ever really needed to grab anything but tracks using the Soundcloud API. Hope this helps, though I'm not sure I fully understand what it is that you are trying to accomplish (or rather, how exactly you're going about it) - are you trying to allow user logins? If you want to explain fully what you're trying to accomplish and the steps you're taking I'd be happy to take a crack at it.
Yep, this is the way to do it, officially. :)
For the Next SoundCloud site, we store the token in localStorage (until the user logs out, of course). In each AJAX request to the API from the front end, we put the oauth token in a request header:
jqXHR.setRequestHeader('Authorization', 'OAuth ' + the_oauth_token);

Redirecting requests form a catch-all controller in Zend Application without looping forever

There are plenty of related posts to what I'm asking, but after some lengthy searches couldn't quite find what I was looking for, my apologies if it exists somewhere.
My goal -- ALL requests to my Zend App must go through a preDispatch plugin, then pass to a custom Auth controller that will decide whether existing auth credentials are sufficient for the requested operation. 'Sufficient' depends on the logic of the app, hence why I want to do this at the controller+model level. If they suffice, they send the original request along to the specified controller+action, if not they default to a 'get lost' action.
At present I'm using an auth custom plugin set in the preDispatch to simply check for POST'ed auth credentials (if we are logging in), then in all cases the plugin stores the original request and redirects everyone (auth'd or not) to my auth controller, a-la:
$request->setModuleName('default')
->setControllerName('auth')
->setActionName('check')
->setParam('oreq',$request->getParams());
My problem/question is that within my auth->check action, how should I perform the redirect after a decision is made? If I use:
$this->_helper->redirector($or['action'], $oreq['controller']);
then I obviously get an infinite loop as these requests pass through the preDispatch plugin again. Sure I could pass something with the redirect so that the Auth plugin ignores such requests, but this is clearly a security hole. I had thought about maybe generating and storing an md5 hash, storing it to session and passing that as an escape param, but that seems a little sketchy.
Any better ideas out there? Perhaps a redirect method that does not go through the standard predispatch routine in Zend App? Thanks in advance!
This is not how it is done usually in Zend Framework. Not all requests go to a common place and gets redirected to the original requested place authentication.
For access control, use Zend_Acl. Through that, you could easily determine whether the current user has the necessary auth to access the content, else redirect to 'get lost' action.
If you are still adamant on using your technique, use _forward method instead of redirect method.
Since _forward is an internal redirect, you could pass additional arguments and check that in preDispath to avoid a loop.
$this->_forward($action, $controller, $module, $params)