Well, I'm working on a mobile application with ionic framework. In one of my views, the user can edit your name, password and also its image. For this I am using the CordovaFileTransfer plugin and it works great for me. I'm managing to change the image and all the data I need. But not even like getting to change the data in my database, update the application. Let me explain.
When the user changes their image or their data, the web service response returns a "status 1" if achievement make the change successfully and also the URL of the image and the new name change. This we have in localStorage variables and $ rootScope within my application which update once it receives a status one from my server but to return to my dashboard application that is not updated, I close and open the application again and reflected the changes. As a way to do it, maybe my question is very basic but that works for more than one person.
JSON WEBSERVICE RESPONSE :
Object {status: 1, photo: "www.google.cl/de5a0cc049d0f3c394befb83d2cb44e3.jpg", name: "Test"}
Code controller angularjs
$cordovaFileTransfer.upload(encodeURI(server),image,ftOptions,true)
.then(function(result) {
var respuestaJSON = jQuery.parseJSON(result.response);
if(respuestaJSON.status == 1){
sessionService.set("user",respuestaJSON.name);
sessionService.set("photo", respuestaJSON.photo);
$rootScope.username = sessionService.get("user");
$rootScope.photo = sessionService.get("photo");
sessionService :
.factory('sessionService',['$http',function($http){
return {
set:function(key,value){
return localStorage.setItem(key,JSON.stringify(value));
},
get:function(key){
return JSON.parse(localStorage.getItem(key));
},
destroy:function(key){
return localStorage.removeItem(key);
},
};
}])
HTML CODE :
<div id="dashboard-header">
<center>
<div id="home-avatar" style="background-image:url('{{photo}}')"></div>
</center>
</div>
Related
I am working on an application, in which a user if has an account in db can log in the website and then perform certain functions. One of those functions involve creating a blog. The blog is being displayed in another project application using the same database. Now when user creates a blog after logging in, i need to store who created the blog in order to do that, i came up with 2 ways. Either i keep passing the user id as a parameter on every page url or i can create a session in order to store it for the duration of login.
I think the latter is a better option but i am kind of lost on how to do it. I am creating a 3 project layer Application. with the client side done in angularjs. My c# controller is being used just to pass the json data to another layer, which then communicates with the database which is in another layer.
The project files are too big but i can write a example code for it.
Html:
<div ng-app="Module">
<div ng-controller="AppController">
<input ng-model="user.Email" type="email"\>
<button type="button" ng-click="UserLogin()"\>
</div>
</div>
AngualrJs:
var app = angular.module('Module', []);
app.controller("AppController", function ($scope) {
$scope.loginchk = function () {
Post("/User/LoginValidation", $scope.user, false, $("#btnlogin")).then(function (d) {
if (d.Success) {
window.location.href = "/User/LoggedIn?emailId=" + $scope.user.Email;
}
ShowMessage(d);
});
}
})
Controller:
public JsonResult LoginValidation(LoginUser user) {
return Json((new userLogic()).LoginChk(user), JsonRequestBehavior.AllowGet);
}
Business Logic LAYER----------------
UserLogic:
public Message LoginChk(LoginUser user) {
Message msg = new Message();
try {
Account userProfile = db.Accounts.Where(b => b.Email == user.Email).FirstOrDefault();
if (userProfile == null)
{
msg.Success = false;
msg.MessageDetail = "Account Email does not exist";
}
else
{
if (userProfile.password != user.Password)
{
msg.Success = false;
msg.MessageDetail = "Wrong Password";
}
else
{
msg.Success = true;
msg.MessageDetail = "Logged In";
}
}
}
catch(Exception ex)
{
msg.Success = false;
msg.MessageDetail = "DB connection failed.";
}
return msg;
}
Now I know i can create a Session Variable in the controller like this Session['Sessionname'] = user;
but i am not sure it will work with my application because i have multiple controllers and i will still have to pass it to them. so i dont see the point of maintaining a session variable in every controller even if its not used. How do i go about creating a session?
local storage is best option to do that :
window.localStorage.setItem("userId",useId);
to get again:
localStorage.getItem("userId");
You Can use client-side LocalStorage to save the user-id and use it where ever necessary,
as it will be saved in plain text you can encrypt and save it .
check here how to encrypt using javascript
https://stackoverflow.com/a/40478682/7262120
I am learning React and want to create an application with Symfony4 as my backend and React frontend. I am stuck now when I need to pass some kind of data to the frontend from my backend. I don't really know what is the right way to do it? Following some tutorials I am doing it like this:
From the controller I send some data to the twig file:
/**
* #Route("/")
*/
public function homepage()
{
$date = new DateTime();
$curr_date = $date->format('Y-m-d H:i:s');
return $this->render('base.html.twig', [
'gameDate' => $curr_date
]);
}
In the twig file, I set it as a data-attribute
base.html.twig:
<div id="root" data-event-date="{{ gameDate }}">
Then I can get the variable as a dataset in my JavaScript
App.js:
const root = document.getElementById('root');
ReactDOM.render(<Homepage {...(root.dataset)}/>, root);
And render it from props.
Homepage.js:
class Homepage extends Component {
constructor(props) {
super(props)
this.state = {
prizePool: '',
gameDate: '',
numberOfPlayers: ''
}
}
onParticipateClick = (event) => {
this.setState({prizePool: Math.random()})
}
render()
{
return (
<div className="mt-c-10">
<GameInfoBox gameDate={this.props.eventDate}/>
</div>
)
}
}
This actually works, but I am concerned with showing all the information in data variables because anyone can see it. What if I want to pass user ID or something secret? There should be another way to do it right?
It depend on what you attemps, if you are working on big project, you can use API to serve backend data. Take a look here: https://www.modernjsforphpdevs.com/react-symfony-4-starter-repo/. There is a simple example.
But if you want something more use api-platform or FOSRestBundle.
"Best and safest" is a little ambiguous - do you need strict security, or safe as in code stability etc?
Instead of passing your data from controller to view (twig) and then into HTML elements or global, another way is this:
Controller loads the view file with your nav and other stuff
Controller loads React (however you do this, Webpack etc)
React calls another controller (i.e. fetch()). This controller is probably somewhere like src/Api/Controller/ as it wont render a view so keep it separate to the other controllers which do render a view
The API controller calls your DB or remote API (etc) and gets the data and sends it back as JsonResponse back to React.
React can then show the data, or an error message depending on the response status
The API controller in your MW can also handle errors and do some logging, so React just gets a 200 and the data or a 400 (or whatever) and it can show a nice message to the user as normal.
This problem of displaying images on the angular client has disturbed me for long time, even after reading many similar questions. files are uploaded successful to the upload folder and the file details are stored in the mongodb database.
This is angular client. angular v1.6 after loading image data service or factory.
$scope.attachImages.push({
name: attachment.originalName,
filePath:attachment.upload_path
})
Then the html web page has this where I use the ng-src for image upload path.
<div layout = "column" ng-repeat ="image in attachImages">
<h5>{{image.name}}</h5>
<img ng-src="{{image.filePath}}"/>
</div>
But this is the error I get where it cannot load the images:
GET http://localhost:3010/client/upload/attachment/lion.jpg 404 (Not
Found)
this is what i did on the express nodejs backend server
router.get('/attachments/:cardId', function(req,res){
//load teh attachemnts from the db... imageId,
/// To get all the images/files stored in MongoDB
Attachment.find({card: req.params.cardId}, function(err,images){
if (err) {
res.json({"success": false, "message": 'Error finding the attachments'})
} else {
res.json({"success": true, "message": images})
//for teh single image..
router.get('/attachments/:cardId/:attachmentId',function(req,res){
Attachment.findOne({_id: req.params.attachmentId}, function(err, image){
if (err) {
res.json({"success": false, "message": 'ERror in finding the image'})
} else {
if (image) { //atleast there z content
//set the content-type correctly so our client or browser know how to handle it.
res.setHeader('Content-Type', image.mime);
//fs.createReadStream(path.join(UPLOAD_PATH, result.filename)).pipe(res);
//fs.createReadStream(path.join()).pipe(res);
res.send(image.upload_path);
}else {
res.json({"success": true, "message": 'No image data found'})
}
}
})
});
Please any help will be appreciated... Then later I'm going to talk about createObjectURL method, which does not show anything except gibberished arrays data.
I realised that i had made a mistake on the filePath while loading the images.
it is better for one to first test whether you can load images in the browser from their upload path first before sending the images.
just putting this express static handler before loading routes saved me after struggling for a week trying to load images.
app.use(express.static(__dirname + '/client'));
app.use(express.static(__dirname + '/client/upload/attachment'));
then load the express routes
//var user = require('./routes/user') //user routes
board = require('./routes/board'),
then on the angular client
if(attachName.match(/\.(jpg|jpeg|gif|png)$/)){ //u borrowed this from helper in nodejs
//console.log('yeah it z the image')
//$scope.attachImages.push(attachment);
$scope.attachImages.push({
name: attachment.originalName,
imageUrl: attachment.upload_path
})
I have a put method inside my web API controller. The site has a view mode and an edit mode. When the user is in Edit mode it should save the data into the database(because there are currency changes). When the user is on the view mode page it will still calculate the currency changes but it shouldn't be saved into the database.
So inside my method I have a condition in which mode the user is. When it is edit mode it should calculate and save it. When the user is in view mode it only should calculate it and return the object so I can use it client side.
if (isEditMode)
{
_currencyConversionService.ApplyCurrencyRateToCarearRequest(request);
_requestRepository.Save(request);
}
else
{
_currencyConversionService.ApplyCurrencyRateToCarearRequest(request);
}
return Ok(request);
In edit mode the data is saved when the user clicks the confirmation button. But I'm getting an error clientside though:
net::ERR_SPDY_PROTOCOL_ERROR
Is this because I just return the request inside the Ok() that i'm getting this error or why do I get this one? I'm ending up into the catch from this code:
this.service.save(this.model, this.isEditMode)
.then((response: any) => {
debugger;
this.messageService.success('request.notifications.currencySaved');
this.close();
this.$timeout(() => {
this.$window.location.reload();
}, 1000);
}).
catch((reason: any) => {
debugger;
});
How can I return an object inside a PUT method?
Thanks, Brent
I'm using meteor ui twitter accounts. What I'm attempting to do is basically delete all the users from the Meteor collection when the button clear is clicked on. This is my code:
HTML File:
<div ng-controller="TweetsCtrl">
<meteor-include src="loginButtons"></meteor-include>
<ul>
<br>
<div ng-repeat="t in twitterAccs">
<img src = "{{t.services.twitter.profile_image_url_https}}">
<br>
<i>#{{t.services.twitter.screenName}}</i>
<br>
<br>
</div>
<button ng-click="clearUsers()">Clear</button>
</ul>
JS File:
if (Meteor.isClient) {
angular.module('twitter-example',['angular-meteor']);
angular.module('twitter-example').controller('TweetsCtrl',['$scope','$meteor',function($scope,$meteor) {
$scope.twitterAccs = $meteor.collection(Meteor.users);
$scope.clearUsers = function () {
$scope.twitterAccs = $meteor.collection(Meteor.users.remove({}) );
console.log("hello");
}
}]);
}
I assume this is only for development purposes right? It would suck to allow a visitor to your site to delete all your users. The fact you have a nice button set up for it has me worried it's a feature!
The easiest way to do it is hook up a Meteor.method like
if (Meteor.isServer) {
Meteor.methods({
clearUsers: function() {
Meteor.users.remove({});
}
});
}
Then do a Meteor.call('clearUsers') where your console.log("hello") is. You can also run the call via the browser console, I do this setup sometimes instead of going directly to the db via the terminal.
You could also do it via allow deny rules (see: http://docs.meteor.com/#/full/allow), by default a rule is setup so a user can only edit their own profile object.
Lastly you could include the meteor package insecure (I assume you must have already removed it) which will allow anyone to edit any collections assuming you haven't set up any of the allow, deny rules mentioned above.