Need to create a controller that deactivates a user. - spring

The following code is the deactivate method:
#RequestMapping(method=RequestMethod.POST, value = "/deactivate")
public boolean deactivateAccount(#RequestBody SomeReqBean someReqBean) {
//code already finished
}
I am looking to see how I can go about creating a controller that will allow me to deactivate a user upon request from a submit button.

For what I understood from your question is that you want to deactivate a user after clicking on submit button.
There're several ways to do that.
The simpler way is that :--
1.) Create a column in your user table by the name 'status' (or anything you want)
2.) When you're creating a user save the value of that 'status' column to 1 for that userID (status = 1 means, this user is currently in active state)
3.) Now, when you want to deactivate that user, simply update that 'status' value to 0
So, your code will be something like this :---
#RequestMapping(method=RequestMethod.POST, value = "/deactivate")
public boolean deactivateAccount(#RequestBody String user_id) {
boolean statusFlag = your further query to update user's status field in DB to 0
if(statusFlag){
//means status is successfully updated in DB
return true;
}else{
return false;
}
}

Related

Laravel 4 - Check if a database value is true

Im running Laravel 4 for my app ... Im a newbie.
I have created a small little application using the standard built in authentication and everything is working fine.
I have the User.php model and the routes file taking care of all my requests.
What i want to do, is add administrators, i have added a field in my users table which is named 'is_admin' .. its an integer of 1 or 0.
What i want to be able to do is something like the following
if is_admin() {
// Do stuff here if im an admin
}
Can anyone help me out with how i can achieve that .. All i have at the moment is a database column.
Cheers,
Actually you may check if the user is an admin ot not using this:
if(Auth::user()->is_admin) {
//...
}
Because Auth::user() returns the currently logged in user and is_admin field is available in the users table so if a user is logged in then you may simply check by checking the Auth::user()->is_admin property of the logged in user model. If a user is admin then the value is 1 and this will be true and for 0 result will be false in the if condition.
If you want to add a method in the user model then you may try this way:
public function isAdmin()
{
return $this->is_admin;
}
So you may check like:
$user = User::find(1);
if($user->isAdmin()) {
//...
}
$val = (bool)DB::table(DB::raw('DUAL'))->whereExists(function($query) use ($userId)) {
$query->from = 'users';
$query->where('id', $userId)->where('is_admin', 1)->select(DB::raw(1));
})->first([DB::raw(1)]);
This will run a SELECT 1 FROM DUAL WHERE EXISTS (SELECT 1 FROM users WHERE id = X and is_admin = 1 query which will return a boolean if the row exists or not.
DUAL is a dummy table in MySQL and used so we don't have to go trough a table. DB::raw(1) is used as we don't need to fetch column data for this, we just want true/false.
If you're already logged and you're using Laravels Auth you can just do as #WereWolf mentioned.

Save and Update in a controller together in Yii

There are two tables in my db, users and profile. Profile has user_id as a primary key. Every user can have only one profile. When I upload a image file its name is stored in profile table with that user_id. When there are other fields to be updated in profile table, I first check whether there is already a record with that user_id. In my Profile model I have written
public function checkForSaveOrUpdate()
{
return self::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
}
and my controller file looks something like this
public function actionCreateInfo()
{
$profile = new Profile;
$profile->user_id = Yii::app()->user->id;
if(isset($_POST['Profile']))
{
if($profile->checkForSaveOrUpdate() === null)
{
$profile->attributes = $_POST['Profile'];
if($profile->save())
Yii::app()->user->setFlash('success','Profile has been saved successfully');
}
elseif($profile = $profile->checkForSaveOrUpdate())
{
$profile->attributes = $_POST['Profile'];
if($profile->update())
Yii::app()->user->setFlash('success','Profile has been updated successfully');
}
$this->redirect(array('index'));
}
$this->render('createInfo',array('profile'=>$profile));
}
My problem is when I already have a record in database,in profile, and I submit a new form the old data is all deleted and only the current values submitted are updated, whereas it should keep the old values and only update the new ones.
If you instaciate the model like:
$model = new YourModel;
you will have the $model->isNewRecord set to true:
var_dump($model->isNewRecord); // true, in this case you use $model->save()
When you find a record, the same property will have the opposite value:
$model = YourModel::model()->findByPk(1);
var_dump($model->isNewRecord); // false - and now you use $model->update(), instead.
Change your function to static function
public static function checkForSaveOrUpdate()
{
return self::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
}
Then modify action as
public function actionCreateInfo()
{
$profile = Profile::checkForSaveOrUpdate();
if($profile===null)
{
$profile=new Profile;
$profile->user_id = Yii::app()->user->id;
}
if(isset($_POST['Profile']))
{
$profile->attributes = $_POST['Profile'];
if($profile->save())
Yii::app()->user->setFlash('success','Profile has been saved successfully');
$this->redirect(array('index'));
}
$this->render('createInfo',array('profile'=>$profile));
}
Your POST data probably includes all model attributes, including those left blank by the user set to the empty string; the empty string is an accepted value for massive assignment unless otherwise stated in the model rules; a massive assignment is what you actually do with $profile->attributes = $_POST['Profile'];.
One solution would be to unset those attributes that you don't want to update, e.g. those containing an empty string, in the controller.
But this kind of rule should be defined in the model and triggered by calling the validate() method, which you are now skipping by calling update(). You better call save() because internally calls validate() as opposed to update().
A rule for a default value is defined like this:
array(
'attr_name',
'default',
'setOnEmpty' => true,
'value' => null
)

Set passed value in my ActionResult

I have two independent classes that model my tables. First when a new user is created, the user does not have a record in the certificate tables. So in the view for the certificates I have added a button to add certificates details for this new user.
This is my code for the user view: I omitted the paging/search and filter code to make it simple
public ActionResult Index()
var recipients = from s in db.User
select s;
return View(recipients.ToList());
This is the details view showing related data:
public ViewResult Details(int id)
{
var certificateDetails = db.Certificate.Where(p => p.ID == id);
return View(certificateDetails);
}
Adding a new user means also adding a new certificates details. I want when a user clicks details for the a particular user if those details aint around to be redirected to a create certificate view with both User.ID and CertificateID set. In fact CertificateID is AI but ID from User is foreign key.
I would have used Fluent API but am not good with it either so have to handle this seemingly small challenge in code.
If I understand your question correctly, you want it so that when you view Details(), if the certificate details don't exist, then redirect to a page to create them?
Just check whether or not the entity exists. If it doesn't, return a RedirectToAction() and pass whatever data you need in the route data collection.
public ViewResult Details(int id)
{
var certificateDetails = db.Certificate.FirstOrDefault(p => p.ID == id);
if (certificateDetails == null)
return RedirectToAction("Create", "Certificate", new { userId = id });
return View(certificateDetails);
}
You'll also need to create a Certificate controller with a Create() action.

MVC3 URL parameters - avoiding malicious attacks/security flaws

When navigating to a new webpage, is there a "Best Practice" for passing Ids around.
For example, a person registers to use a website, they get given an Id, this needs to be passed around the rest of the website/pages where it is used to retrieve relevant data from a database.
If the Id is passed in the url: http://myWebsite.com/User/Details/1234, the user could change it to
http://myWebsite.com/User/Details/4567 and potentially retireve a different user's details.
Putting this value in a hidden field and then POSTing wouldn't be great either as "view source" would display the value.
Many thanks
That's why you should always verify that this id belongs to the currently authenticated user. The currently authenticated user is stored in the forms authentication cookie and is something that the user cannot change because the value is encrypted. This cookie is emitted when the user logs in and you can access it everywhere where you have an instance to HttpContextBase (which is pretty much almost anywhere in the V and C parts of the MVC pattern).
For example, like this:
[Authorize]
public ActionResult Foo(int id)
{
string currentUser = httpContext.User.Identity.Name;
// TODO: go ahead and check in your backed that the id
// belongs to the currently connected user
...
}
Obviously writing those checks over and over again in all controller actions could quickly become boring, not to mention the DRYness of the approach. That's why it is recommended to write a custom Authorize attribute which will perform those checks before even entering into the controller action. Then you will decorate your controller actions with this custom attribute and you will know for sure that if the code has reached inside the action it means that the current user is the owner of the id passed as parameter. The way this id is passed as parameter doesn't really matter. Could be route data, query string, POST, whatever. The user can modify it as much as he likes. The important part is that you ensure that the value he entered is coherent with your domain authorization logic.
So:
public class AuthorizeOwnerAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
// the user is either not authenticated or not authorized
// no need to continue any further
return false;
}
// at this stage we know that the user is authenticated and
// authorized (in roles), so let's go ahead and see who this
// user is
string username = httpContext.User.Identity.Name;
// now let's read the id. In this example I fetch it from
// the route data but you could adapt according to your needs
string id = httpContext.Request.RequestContext.RouteData.Values["id"] as string;
// Now that we know the user and the id let's go ahead and
// check in our backend if the user is really the owner
// of this id:
return IsOwner(username, id);
}
private bool IsOwner(string username, string id)
{
// go ahead and hit the backend
throw new NotImplementedException();
}
}
and then:
[AuthorizeOwner]
public ActionResult Foo(int id)
{
...
}

Displaying records from database which are equal to logged on user

I have created an MVC3 application which needs to show user specific data. The problem I am having is trying to display records which are equal to #user.Identity.Name.
The following Linq to SQL has been used to try to accomplish this:
public ActionResult Index()
{
using (var db = new mydatEntities())
{
var details = from t in db.testadtas
where t.UserID == Viewbag.UsersRecord
select t;
return View();
}
}
(Update)
New to c# and Linq and finding it hard to write a query which will only display the logged on users records.
I have used the code below
MembershipUser currentUser = Membership.GetUser (User.Identity.Name, true /* userIsOnline */);
Viewbag.UsersRecord = currentUser.ProviderUserKey;
I have then input the Viewbag.UserRecord into a textbox which updates a database field with the UserID in a table I have created.
I now want to write a linq query to say if UserID = Viewbag.UserRecord then show record with the UserID only
Is this a correct method to use for showing logged on user records?
or is there any other way which I can implement this in MVC3?
Just use HttpContext.User.Identity.Name

Resources