Auth::check() not working Laravel 5.5 - laravel-5.5

In my model i have a method
public function newUserUpload(string $save_path){
$this->photo_moderation_src = $save_path;
if(Auth::check()){
$this->user_id = Auth::id();
}
$this->save();
return null;
}
After authorization i try to upload file but the record in the database is created without user_id. At the same time the authorization check in my blade is working correctly.
#if (!Auth::check())
<li>Auth</li>
#else
<li>Exit</li>
#endif
Could this be due to the fact that I use vueJs + Laravel api routes?
Route::middleware('api')->group(function(){
Route::post('/upload/', 'CompgenApiController#userUpload');
Route::post('/reupload/', 'CompgenApiController#moderationReupload');
});

use Auth;
or use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Auth;
if (Auth::check()) {
// The user is logged in...
}
or
if (\Illuminate\Support\Facades\Auth::check()) {
// The user is logged in...
}
for user id u can use Auth::user()->id or something else in users table, like:
Auth::user()->hasRole, Auth::user()->registrationCompleted
public function newUpload(string $save_path){
if(!Auth::check()){ return false }
// if(!Auth::user()->registrationCompleted){ return false }
// other Security measures
$newUpload = new Pic(); // pics table in dataBase
$newUpload->photo_moderation_src = $save_path;
$newUpload->user_id = Auth::user()->id;
$newUpload->save();
return true;
}

Related

Salesforce Apex web service test class error

I'm working on Salesforce Apex web service to create record. Below is the apex web service class that I have written:
global class createCloudRecord {
global class projectInputs{
webService Integer ProjectID;
webService String ProjectName;
}
webService static Boolean createSFRecords(List<projectInputs> inputs) {
cv__Designation__c desg = new cv__Designation__c();
desg.cv__Active__c = true;
desg.cv__Default__c = false;
desg.cv__Description__c = 'Test Desc';
desg.OwnerId = '002B0000000K9soIAD';
desg.Name = inputs[0].ProjectName;
desg.cv__ExternalId__c = string.valueof(inputs[0].ProjectID);
insert desg;
return true;
}
}
It's working fine and creating records on SF cloud via SOAP API call. Now I have to written the test class for above web service with code coverage of min 75%.
Below is the code that I have written for my test class:
#isTest
private class createCloudRecordTest {
static testMethod void testCreateSFRecords() {
createCloudRecord.projectInputs project = new createCloudRecord.projectInputs();
project.ProjectID = 12345;
project.ProjectName = 'TestProject';
createCloudRecord.createSFRecords(project);
}
}
But this is showing an error for this line createCloudRecord.createSFRecords(project);:
Error: Compile Error: Method does not exist or incorrect signature.
Anyone has any idea how can I make this working.
Thanks!
I got the solution for my question. The problem was in my web service I've defined param as list but above in test class I'm passing param as single record.
So it should be something like below:
#isTest
private class createCloudRecordTest {
static testMethod void testCreateSFRecords() {
createCloudRecord.projectInputs project = new createCloudRecord.projectInputs();
project.ProjectID = 12345;
project.ProjectName = 'TestProject';
list<createCloudRecord.projectInputs> projects = new list<createCloudRecord.projectInputs>();
projects.add(project);
createCloudRecord.createSFRecords(projects);
}
}

AdMob not working with IF statement?

This code doesn't work. I checked displayLanguage value. Value is right (displayLanguage="Türkçe"). But it doesn't work.
private void setAdvertisement()
{
Locale _locale = Locale.getDefault();
String displayLanguage = _locale.getDisplayLanguage();
if(displayLanguage == "Türkçe")
{
// Create the adView
adView = new AdView(this, AdSize.BANNER, "My Admob ID");
// Lookup your LinearLayout assuming it’s been given
// the attribute android:id="#+id/mainLayout"
// Add the adView to it
linearLayoutAdvertisement.addView(adView);
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
}
}
But this code works fine:
private void setAdvertisement()
{
// Create the adView
adView = new AdView(this, AdSize.BANNER, "My Admob ID");
// Lookup your LinearLayout assuming it’s been given
// the attribute android:id="#+id/mainLayout"
// Add the adView to it
linearLayoutAdvertisement.addView(adView);
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
}
I don't understand what the problem is.
This isn't an AdMob issue. But try this:
if ("Türkçe".equals(displayLanguage)) {
..
}
I solved problem. This worked for me:
if(Locale.getDefault().getLanguage().equals("tr"))
{
...
}

Grails: getting IndexOutOfBoundsException from Datamodel Objects in Service during unit test

I have A simple Customer + PaswordReset datamodel.
In my PasswordService I call PasswordReset.findByUsername() and save() and it works fine.
I then made PasswordServiceTests which has #Mock([Customer, PasswordReset])
In that test I create a new Customer object and use Customer.save and use PasswordReset.findByUsername(). Both work fine.
The test call service.initatePasswordReset() (PasswordService) which uses both Customer.findByUsername() and PasswordReset.save() successfully.
In the test I then call PasswordReset.findByUsername(...) and find the object made by the service.initiateReset().
But when I call another method: service.performReset(), which successfully loads the customer object by using Customer.findByUsername(..), modifies the customer password field and tries to do customer.save()
The following error is caused by the customer.save() in the PasswordService. Can anyone tell me what is wrong?
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.remove(ArrayList.java:445)
at org.grails.datastore.mapping.simple.engine.SimpleMapEntityPersister$1.deindex(SimpleMapEntityPersister.groovy:101)
at org.grails.datastore.mapping.engine.NativeEntryEntityPersister.updatePropertyIndices(NativeEntryEntityPersister.java:1200)
at org.grails.datastore.mapping.engine.NativeEntryEntityPersister.access$100(NativeEntryEntityPersister.java:55)
at org.grails.datastore.mapping.engine.NativeEntryEntityPersister$4.run(NativeEntryEntityPersister.java:958)
at org.grails.datastore.mapping.core.impl.PendingOperationExecution.executePendingOperation(PendingOperationExecution.java:36)
at org.grails.datastore.mapping.core.AbstractSession.flushPendingOperations(AbstractSession.java:323)
at org.grails.datastore.mapping.core.AbstractSession.flushPendingUpdates(AbstractSession.java:302)
at org.grails.datastore.mapping.core.AbstractSession.flush(AbstractSession.java:240)
at org.grails.datastore.gorm.GormInstanceApi.doSave(GormInstanceApi.groovy:168)
at org.grails.datastore.gorm.GormInstanceApi$_save_closure4.doCall(GormInstanceApi.groovy:143)
at org.grails.datastore.mapping.core.DatastoreUtils.execute(DatastoreUtils.java:301)
at org.grails.datastore.gorm.AbstractDatastoreApi.execute(AbstractDatastoreApi.groovy:34)
at org.grails.datastore.gorm.GormInstanceApi.save(GormInstanceApi.groovy:142)
at com.foo.services.PasswordService.performPasswordReset(PasswordService.groovy:33)
at com.foo.services.PasswordServiceTests.testResetPassword(PasswordServiceTests.groovy:47)
PasswordServiceTest.groovy
#TestFor(PasswordService)
#Mock([Customer, PasswordReset])
class PasswordServiceTests {
void setUp() {
mockCodec(MD5Codec)
// mockService(CustomerRegistrationService)
}
void testResetPassword() {
Customer c = CustomerRegistrationServiceTests.makePrivateCustomer()
c.sumUnpaidInvoices = 0
c.sumOverdueInvoices = 0
c.password = service.hashPassword(c)
c.customerType = CustomerType.NormalCustomer.value
c.save(flush: true);
assertEquals("Mock DB does not contain 1 customer", 1, Customer.list().size())
service.initiatePasswordReset(c.username)
def pwReset = PasswordReset.findByUsername(c.username)
println("psreset saved: " + pwReset.username + " / " + pwReset.code)
assertEquals(c.username, pwReset.username)
service.performPasswordReset(c.username, "test"); // CALLS METHOD BELOW
}
}
Method in PasswordService.groovy:
def performPasswordReset(String username, String newPassword) {
Customer customer = Customer.findByUsername(username)
if(customer != null) {
customer.password = newPassword;
customer.password = hashPassword(customer);
customer.save(flush: true); // CAUSES THE ERROR
....
}
}
I fixed this problem by removing the call to customer.save() in the service, it was not required and even without customer.save the password is still stored to database automatically when you change it (customer.password = "foo").
It looks like this particular error is not really related to
customer.save(flush: true);
I'd say that hibernate has something else that needs to be persisted (any previous "non-flush save") and that fails.

OAuth making requests against LinkedIn API cause 401 error

I am creating an application for a client that integrates with the LinkedIn API. I got through the authentication without too many problems, but everything there is working and now I need to make the actual requests. Primarily I am working in the Share API. I create the HTTP call with the following method:
public any function sendRequest(any req){
var param = false;
var headParams = [];
var bodyParams = [];
var call = new http(proxyserver='192.168.201.12', proxyport=8888);
var i = 1;
call.setUrl(Arguments.req.getRequestUrl());
call.setMethod(Arguments.req.getMethod());
getSigner().signRequest(Arguments.req);
headParams = Arguments.req.getParameters(true);
bodyParams = Arguments.req.getParameters();
if(arrayLen(bodyParams)){
call.addParam(
type='header',
name='Authorization',
value="OAuth#Variables.encoder.encodedParameter(Arguments.req.getParameters(true), true, false, true)#"
);
}
// Header parameters
if(!arrayLen(bodyParams)){
for(i=1; i<=arrayLen(headParams); i++){
param = headParams[i];
call.addParam(
type=Arguments.req.getParameterType(),
name=Variables.encoder.parameterEncodedFormat(param.name),
value=param.value
);
}
}
// Body parameters (should only be 1)
if(arrayLen(bodyParams)){
for(i=1; i<=arrayLen(bodyParams); i++){
param = bodyParams[i];
call.addParam(
type='xml',
value=param.value
);
}
}
return call.send().getPrefix();
}
When I sign the request, I use the following method:
public void function signRequest(any req){
var headParams = Arguments.req.getParameters(true);
var bodyParams = Arguments.req.getParameters();
var secret = "#Variables.encoder.parameterEncodedFormat(getConsumer().getConsumerSecret())#&#Variables.encoder.parameterEncodedFormat(Arguments.req.getOAuthSecret())#";
var base = '';
params = Variables.encoder.encodedParameter(headParams, true, true);
params = "#params#&#Variables.encoder.parameterEncodedFormat(bodyParams[1].value)#";
secret = toBinary(toBase64(secret));
local.mac = createObject('java', 'javax.crypto.Mac').getInstance('HmacSHA1');
local.key = createObject('java', 'javax.crypto.spec.SecretKeySpec').init(secret, local.mac.getAlgorithm());
base = "#Arguments.req.getMethod()#&";
base = base & Variables.encoder.parameterEncodedFormat(Arguments.req.getRequestUrl());
base = "#base#&#Variables.encoder.parameterEncodedFormat(params)#";
//writeDump(base) abort;
local.mac.init(local.key);
local.mac.update(JavaCast('string', base).getBytes());
Arguments.req.addParameter('oauth_signature', toString(toBase64(mac.doFinal())), true);
}
I have tried signing it with only the header parameters (usual OAuth params) and include the body parameter (xml string), but everything gives me a 401 error, so I was wondering what I should be using in my base string that gets signed for the request?
Not a proper answer to your question, but may help you.
In my case after many unsuccessful tries of using the LinkedIn API with CF8, I finally gave up / didn't have more time for it. Instead of a "proper" integration I've used the linkedin-j Java library. It finally got me going and I didn't encounter any more signing issues.
Btw for all my integrations requiring OAuth I've used this library and didn't have any signing issues as with LinkedIn API.

Using the Reporting Services Web Service, how do you get the permissions of a particular user?

Using the SQL Server Reporting Services Web Service, how can I determine the permissions of a particular domain user for a particular report? The user in question is not the user that is accessing the Web Service.
I am accessing the Web Service using a domain service account (lets say MYDOMAIN\SSRSAdmin) that has full permissions in SSRS. I would like to programmatically find the permissions of a domain user (lets say MYDOMAIN\JimBob) for a particular report.
The GetPermissions() method on the Web Service will return a list of permissions that the current user has (MYDOMAIN\SSRSAdmin), but that is not what I'm looking for. How can I get this same list of permissions for MYDOMAIN\JimBob? I will not have the user's domain password, so using their credentials to call the GetPermissions() method is not an option. I am however accessing this from an account that has full permissions, so I would think that theoretically the information should be available to it.
SSRS gets the NT groups from the users' NT login token. This is why when you are added to a new group, you are expected to log out and back in. The same applies to most Windows checks (SQL Server, shares, NTFS etc).
If you know the NT group(s)...
You can query the ReportServer database directly. I've lifted this almost directly out of one of our reports which we use to check folder security (C.Type = 1). Filter on U.UserName.
SELECT
R.RoleName,
U.UserName,
C.Path
FROM
ReportServer.dbo.Catalog C WITH (NOLOCK) --Parent
JOIN
ReportServer.dbo.Policies P WITH (NOLOCK) ON C.PolicyID = P.PolicyID
JOIN
ReportServer.dbo.PolicyUserRole PUR WITH (NOLOCK) ON P.PolicyID = PUR.PolicyID
JOIN
ReportServer.dbo.Users U WITH (NOLOCK) ON PUR.UserID = U.UserID
JOIN
ReportServer.dbo.Roles R WITH (NOLOCK) ON PUR.RoleID = R.RoleID
WHERE
C.Type = 1
look into "GetPolicies Method" you can see at the following link.
http://msdn.microsoft.com/en-us/library/reportservice2010.reportingservice2010.getpolicies.aspx
Hopefully this will get you started. I use it when copying Folder structure, and Reports from an old server to a new server when I want to 'migrate' my SSRS items from the Source to the Destination Server. It is a a Method to Get the Security Policies for an item on one server, and then set the Security Policies for an identical item on another server, after I have copied the item from the Source Server to the Destination Server. You have to set your own Source and Destination Server Names.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Web.Services.Protocols; //<=== required for SoapException
namespace SSRS_WebServices_Utility
{
internal static class TEST
{
internal static void GetPoliciesForAnItem_from_Source_ThenSetThePolicyForTheItem_on_Destination(string itemPath)
{
string sSourceServer = "SOURCE-ServerName";
Source_ReportService2010.ReportingService2010 sourceRS = new Source_ReportService2010.ReportingService2010();
sourceRS.Credentials = System.Net.CredentialCache.DefaultCredentials;
sourceRS.Url = #"http://" + sSourceServer + "/reportserver/reportservice2010.asmx";
string sDestinationServer = "DESTINATION-ServerName";
Destination_ReportService2010.ReportingService2010 DestinationRS = new Destination_ReportService2010.ReportingService2010();
DestinationRS.Credentials = System.Net.CredentialCache.DefaultCredentials;
DestinationRS.Url = #"http://" + sDestinationServer + "/reportserver/reportservice2010.asmx";
Boolean val = true;
Source_ReportService2010.Policy[] curPolicy = null;
Destination_ReportService2010.Policy[] newPolicy = null;
try
{
curPolicy = new Source_ReportService2010.Policy[1];
curPolicy = sourceRS.GetPolicies(itemPath, out val); //e.g. of itemPath: "/B2W/001_OLD_PuertoRicoReport"
//DestinationRS.SetPolicies(itemPath, newPolicy);
int iCounter = 0;
//int iMax = curPolicy.Length;
newPolicy = new Destination_ReportService2010.Policy[curPolicy.Length];
foreach (Source_ReportService2010.Policy p in curPolicy)
{
//create the Policy
Destination_ReportService2010.Policy pNew = new Destination_ReportService2010.Policy();
pNew.GroupUserName = p.GroupUserName;
pNew.GroupUserName = p.GroupUserName;
Destination_ReportService2010.Role rNew = new Destination_ReportService2010.Role();
rNew.Description = p.Roles[0].Description;
rNew.Name = p.Roles[0].Name;
//create the Role, which is part of the Policy
pNew.Roles = new Destination_ReportService2010.Role[1];
pNew.Roles[0]=rNew;
newPolicy[iCounter] = pNew;
iCounter += 1;
}
DestinationRS.SetPolicies(itemPath, newPolicy);
Debug.Print("whatever");
}
catch (SoapException ex)
{
Debug.Print("SoapException: " + ex.Message);
}
catch (Exception Ex)
{
Debug.Print("NON-SoapException: " + Ex.Message);
}
finally
{
if (sourceRS != null)
sourceRS.Dispose();
if (DestinationRS != null)
DestinationRS.Dispose();
}
}
}
}
To invoke it use the following:
TEST.GetPoliciesForAnItem_from_Source_ThenSetThePolicyForTheItem_on_Destination("/FolderName/ReportName");
Where you have to put your own SSRS Folder Name and Report Name, i.e. the Path to the item.
In fact I use a method that loops through all the items in the Destination folder that then calls the method like this:
internal static void CopyTheSecurityPolicyFromSourceToDestinationForAllItems_2010()
{
string sDestinationServer = "DESTINATION-ServerName";
Destination_ReportService2010.ReportingService2010 DestinationRS = new Destination_ReportService2010.ReportingService2010();
DestinationRS.Credentials = System.Net.CredentialCache.DefaultCredentials;
DestinationRS.Url = #"http://" + sDestinationServer + "/reportserver/reportservice2010.asmx";
// Return a list of catalog items in the report server database
Destination_ReportService2010.CatalogItem[] items = DestinationRS.ListChildren("/", true);
// For each FOLDER, debug Print some properties
foreach (Destination_ReportService2010.CatalogItem ci in items)
{
{
Debug.Print("START----------------------------------------------------");
Debug.Print("Object Name: " + ci.Name);
Debug.Print("Object Type: " + ci.TypeName);
Debug.Print("Object Path: " + ci.Path);
Debug.Print("Object Description: " + ci.Description);
Debug.Print("Object ID: " + ci.ID);
Debug.Print("END----------------------------------------------------");
try
{
GetPoliciesForAnItem_from_Source_ThenSetThePolicyForTheItem_on_Destination(ci.Path);
}
catch (SoapException e)
{
Debug.Print("SoapException START----------------------------------------------------");
Debug.Print(e.Detail.InnerXml);
Debug.Print("SoapException END----------------------------------------------------");
}
catch (Exception ex)
{
Debug.Print("ERROR START----------------------------------------------------");
Debug.Print(ex.GetType().FullName);
Debug.Print(ex.Message);
Debug.Print("ERROR END----------------------------------------------------");
}
}
}
}