Scala-Lift redirect user after login - scala

I want to redirect to a certain page after a user logs in to my Scala Lift web application. I found this answer which doesn't seem to work:
In my User object (which is a MetaMegaProtoUser) I override the following method like so:
object User extends User with MetaMegaProtoUser[User] {
override def loginFirst = If(
loggedIn_? _,
() => {
import net.liftweb.http.{RedirectWithState, RedirectState}
val uri = Full("/myPicks")
println("login sucessful .. redirecting!..")
RedirectWithState(
loginPageURL,
RedirectState( ()=>{loginRedirect.set(uri)})
)
}
)
}
This doesn’t work. Any ideas?

loginFirst defines a LocParam which can be used for specifying where to send the user if they are not logged in. It is used in conjunction with SiteMap.
For the page you want to protect, you can modify that entry like:
Menu("Protected Page") / "protected" >> User.loginFirst
That should test whether the user is logged in when you access /protected and, if they are not, set the loginRedirect SessionVar and display the login form. On a successful login, you should be redirected to the page specified in loginRedirect.
I believe you can also just use: override def homePage = "/myPicks" if you want to set a default page to redirect to.

Related

How to block url that customer type on browser in codeigniter?

I have created a website, And I don't to allowed customer to type link in browser.
I just want to allow customer click link on the website only.
please provide me a solution !!!
thank for help !!!
use token for in hyperlinks . deny if token wont match to value in session.
try the following:
in controller check if session['token'] is set,
if not set session['token'] to a rendom value.
if token not set or won't match to $_GET['token'] variable redirect to error page.
if token match to get variable (ie. $_GET['token']) then , pass that value to view.
i don't recomend this because doing this might affect the browser cache.
Controller constructor
function __construct()
{
parent::__construct();
$this->load->library('session');
if(!isset($_SESSION['token']))
{
$_SESSION['token'] = rand();
}
if((!$this->input->get('token')) || ($this->input->get('token') != $_SESSION['token']))
{
redirect('error_page');
}
// to pass to vew
$data['token'] = $_SESSION['token'];
$this->load->view('view_page',$data);
}
in view_page.php (view) replace links like this
Gallery link

Scala Play session value not saving

So I am working on a webapp in Scala with Play 2.3 using IntelliJ 14.1.1.
The problem is with storing values in the session. I currently have this:
def authCredentials = Action { implicit request =>
loginForm.bindFromRequest.fold(
formWithErrors => BadRequest(views.html.login(formWithErrors.withError("badlogin","Username or password is incorrect."))),
goodForm => Redirect(routes.AccountController.display).withSession(request.session + ("username" -> goodForm._1))
)
}
and then in my AccountController:
def display = Action { implicit request =>
request.session.get("username").map { username =>
Ok(views.html.account(User.getUser(username))).withSession(request.session + ("username" -> username))
}.getOrElse(Redirect(routes.LoginController.login)).withNewSession
}
Now in the the above function it is finding the username and rendering the account page only once. The problem is after that when I want to navigate to a page from the account page such as to the change password page or even a refresh of the account page it will redirect back to login with new session.
What am I doing wrong and is there a better way to check if the session is authenticated for access to the page instead of repeat code on each display function.
It seems to be a simple parentheses problem, try :
def display = Action { implicit request =>
request.session.get("username").map { username =>
Ok(views.html.account(User.getUser(username))).withSession(request.session + ("username" -> username))
}.getOrElse(Redirect(routes.LoginController.login).withNewSession)
}
You were in fact resetting the session in any case in your controller, now the withNewSession call is inside getOrElse, which send a new session only in case of no username found in the current one.

Play framework. How to check if user is authenticated or not?

I'm new to playframework and I'm using version 2.2.2.
I'm checking the zentask sample but could somebody tell me how to check in view if user is logged in or not?
In main.scala.html I've list of links.
<ul>
<li>New blogpost</li>
<li>Login</li>
<li>Logout</li>
</ul>
What I would like to have is that when user is logged in the logout link is shown.
My application.scala looks like this:
def index = Action {
Ok(views.html.index(BlogPost.all(), blogpostForm))
}
I can check that if user is allowed to access to create new blogpost:
def newBlogpost = IsAuthenticated { username => _ =>
User.findByUsername(username).map { user =>
Ok(views.html.blogpost.item(blogpostForm))
}.getOrElse(Forbidden)
}
So what would be the easiest way in main.scala.html to check if user is logged in or not and show correct link based on that?
You can pass session to you html template and check is defined user there or not:
#()(implicit session: Session)
<ul>
#session.get("user").map { user =>
<li>New blogpost</li>
<li>Logout</li>
}.getOrElse{
<li>Login</li>
}
</ul>
Note: you have to mark request in your action as implicit.

How to update securesocial username after user is created

I'm trying to write an editUser page with the Secure Social plugin implemented in a Play Framework app. I'm having trouble staying logged in after the username is changed. The issue occurs when I press submit for the editUser form after changing the username. It goes to the login page and says "You need to log in to access that page." The desired behavior is to redirect to editUser page without needing to relogin. In the database everything is successfully updated. So that works, it just is no longer is logged in.
Below is my controller method for my "User" controller for the POST of the user update.
If anyone could help me out with this it would be greatly appreciated. Thanks.
// The form uses the following case class
case class AccountInfo(userName: String, firstName: String, lastName: String, email: Option[String])
def update(username: String) = SecuredAction { implicit request =>
this.editAccountForm.bindFromRequest.fold (
hasErrors = { info =>
Redirect(routes.Users.edit()).flashing(Flash(editAccountForm.data) +
("error" -> Messages("validation.errors")))
},
success = { info =>
DB.withSession { implicit s: Session =>
val uid = User.currentUser(request.user.id.id,providerId).get.uid
User.update(uid, info, providerId)
}
val message = Messages("user.update.success")
Redirect(routes.Users.edit()).flashing("success" -> message)
.withCookies(request.cookies.get("id").get)
}
)
}
By changing the username you are changing the values used to identify the user (username + provider id). What is happening is that on the next request SecureSocial is looking for the old username and since it can't find it in the database it just kicks you out.
What you should do besides updating the database is update the Authenticator stored for your current session. Something like:
SecureSocial.authenticatorFromRequest(request).map { authenticator =>
val newId = request.user.id.copy( id = userName )
Authenticator.save(authenticator.copy( userId = newId))
}
That should make it work. Also, you don't need to add the id cookie to your Redirect. SecureSocial does that for you.

silverstripe external authentification

there is a custom login form that should give users access to certain contents on the same page. That works so far with Users stored as Members in the SS database and I was checking after Login if the user has permissions like this in the Page Class:
function isAllowed() {
if (Member::currentUser()) {
$PresseGroup = DataObject::get_one('Group', "Code = 'presse'");
$AdminGroup = DataObject::get_one('Group', "Code = 'administrators'");
if (Member::currentUser()->inGroup($PresseGroup->ID) || Member::currentUser()->inGroup($AdminGroup->ID)) {
return true;
}
}
}
in the Template I just did this:
<% if isAllowed %>
SecretContent
<% end_if %>
OK so far, but now the users will not be stored in the silverstripe database - they are stored on a another server.
On that external server is running a little php script accepting the username and password. The script just returns user has permission: true or false.
I´m calling that script via cURL.
I planned to overwrite the dologin Function of MemberLoginForm. Now I just wonder how to check after Login that the User got the permission and display the contents... I tried to set a variable in the controller of the Page or should I set a session Variable? Thats my attempt (CustomLoginForm extends MemberLoginForm):
public function dologin($data) {
if(userHasPermission("user1", "pw")==true){
$this->controller->Test("test");
}
$link = $this->controller->Link();
$this->performLogin($data);
$this->controller->redirect($link);
}
I hope someone can help me with that - I know very specific - problem.
Many thanx,
Florian
In SilverStripe you can create a custom authenticator, which means users can log in on your website with accounts that are stored somewhere else, or even just a hard coded user and password.
You can check out the OpenID Authentication Module for example code on how to do it
But for your task this might even be to complex of a solution, how about after login just do something like Session::set('isAllowed', true); and to check if the user is allowed to view:
function isAllowed() {
if (Member::currentUser()) {
$PresseGroup = DataObject::get_one('Group', "Code = 'presse'");
$AdminGroup = DataObject::get_one('Group', "Code = 'administrators'");
if (Member::currentUser()->inGroup($PresseGroup->ID) || Member::currentUser()->inGroup($AdminGroup->ID)) {
return true;
}
}
// if Member::currentUser() is not allowed to view,
// return the session, which is either set to true or it returns null if not set
return Session::get('isAllowed');
}