koole / react-sanctum Goto Github PK
View Code? Open in Web Editor NEWEasily hook up your React app to Laravel Sanctum and Laravel Fortify
License: MIT License
Easily hook up your React app to Laravel Sanctum and Laravel Fortify
License: MIT License
Hello there!
I am trying to implement this into a new project. Is it possible to redirect the user in case he is not authenticated?
This is what I tried so far but obviously, React is not waiting for react-sanctum to call the API and set the state of the user object.
Is there any way I can redirect the user after the authenticated prop is set as it should be?
class App extends Component {
render() {
if (this.props.authenticated) {
return <MyComponent />;
} else {
window.location.href = 'http://localhost:8000/login'
}
}
}
In the docs, it says:
// {email: string, password: string, remember: true | null} get POSTed to here
signin_route: "api/login",
Does this need to return a plain text sanctum token or something else? Right now my api/tokens request returns a key and it fails via 401 on the /users request.
Hey mate just picked up this library to fool around, noticed there's no way to set my user
type as anything besides what is defined on the library, is there any chance we could add something for it to be useSanctum<TypeDef>()
giving the user whatever the type TypeDef
is?
What im trying to do:
const handleLogin = async (e: any) => {
e.preventDefault();
const {signIn} = React.useContext(SanctumContext);
const sign = await signIn('[email protected]', '12345');
}
Error:
Cannot invoke an object which is possibly 'undefined'.ts(2722) (property) signIn?: ((email: string, password: string, remember?: boolean | undefined) => Promise<{}>) | undefined
Javascripts build in Fetch API is very good! And you don't need a package as Axios.
Hello,
For custom post request using this package, how can I provide CSRF token to my API ?
Because actually, my api returns error 419 unknown status due to csrf token ?
Hi!
Would be nice to make a release to npm with newer axios. Your library use axios "^0.27.2".
Sadly can't use custom axiosInstance with the new axios.
Thank you!
Trying to use react-sanctum
in middleware and I'm getting the following error: TypeError: Cannot read property 'useContext' of null
const { authenticated } = useSanctum();
I have imported useSanctum()
.
Any ideas?
Hi there,
Awesome package!
But I ran into an issue with react 18.2
While using version 2.1.3 i still get the following error:
TS2322: Type '{ children: Element; config: { apiUrl: string; csrfCookieRoute: string; signInRoute: string; signOutRoute: string; userObjectRoute: string; }; checkOnInit: true; }' is not assignable to type 'IntrinsicAttributes & Props'. Property 'children' does not exist on type 'IntrinsicAttributes & Props'.
If I take a look at the Sanctum.d.ts it still looks like this:
import { AxiosInstance } from "axios";
interface Props {
config: {
apiUrl: string;
csrfCookieRoute: string;
signInRoute: string;
signOutRoute: string;
userObjectRoute: string;
twoFactorChallengeRoute?: string;
axiosInstance?: AxiosInstance;
};
checkOnInit?: boolean;
}
declare const Sanctum: React.FC<Props>;
export default Sanctum;
Whilst on your Github there should indeed be a Children element in the props. I'm on version 2.1.3 for sure as my yarn.lock states:
react-sanctum@^2.1.3:
version "2.1.3"
resolved "https://registry.yarnpkg.com/react-sanctum/-/react-sanctum-2.1.3.tgz#acf8f97bb482e1f38130baddf42e92a4b7fbedee"
integrity sha512-J4MPrlSkgY012H1CPQBdQrUFkRkZWMPkSI+HARzw0eigMP1wCAo7hcZNCx153dzIq2Pi9LcbtCeQ0QsYIouYmw==
dependencies:
axios "^0.26.0"
Any way to fix that?
Right now, if you leave your browser window open too long and then attempt to make a request to your laravel application from your React Application, the token times out and the module doesn't automatically refresh the token, there is an error thrown CSRF Token mismatch.
Possibly include a configuration option that automatically enables an axios response interceptor that runs a function from the configuration when status code 419: Session Expired is returned?
As explained here: https://laracasts.com/discuss/channels/general-discussion/detecting-expired-session-with-sanctumspa
This leaves it open for the user to either write a function to reload the window, or reroute the user to re-authenticate, or if they want to try to refresh the session using the csrf method that is already provided.
Property 'then' does not exist on type 'void'.
This is just a type error in?
/src/SanctumContext.tsx
Hi there,
Really like this library, it's been a great help getting up and running with React and Sanctum!
I seem to be having a slight issue when using the signIn function where I am getting "text/plain, /" appended to "application/json" in the Accept header, which in turn is trying to do the normal redirect on login stuff from in Laravel instead of detecting it as an API request. I'm struggling to figure out where this is coming from but am struggling a bit. Can anyone suggest anything where I am going wrong?
I'm using Windows 10 and Brave V1.16.76, but seems to happen on Firefox too.
I've got a react app that will be running on a different domain from my api. My understanding is that I can't use stateful Sanctum logins so Laravel Breeze is a no-go. From the docs it looks like I need to use Sanctum's token login. Does this package support that? Do you have any advice?
When I run npm update, I get these warnings:
npm WARN [email protected] requires a peer of react@^16.13.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of react-dom@^16.13.0 but none is installed. You must install peer dependencies yourself.
This is my package.json:
"dependencies": {
"axios": "^0.21.0",
"next": "10.0.0",
"next-images": "^1.6.2",
"react": "17.0.1",
"react-dom": "17.0.1",
"react-icons": "^3.11.0",
"react-sanctum": "^1.0.0"
},
"devDependencies": {
"@fullhuman/postcss-purgecss": "^3.0.0",
"@types/node": "^14.14.6",
"@types/react": "^16.9.55",
"@typescript-eslint/eslint-plugin": "^4.6.1",
"@typescript-eslint/parser": "^4.6.1",
"autoprefixer": "^10.0.1",
"babel-eslint": "^10.1.0",
"eslint": "^7.12.1",
"eslint-config-airbnb": "^18.2.0",
"eslint-config-airbnb-typescript": "^12.0.0",
"eslint-config-react-app": "^6.0.0",
"eslint-plugin-flowtype": "^5.2.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-react": "^7.21.5",
"eslint-plugin-react-hooks": "^4.2.0",
"postcss-flexbugs-fixes": "^5.0.0",
"postcss-preset-env": "^6.7.0",
"sass": "^1.28.0",
"tailwindcss": "^1.9.6",
"typescript": "^4.0.5"
},
This should fulfill it, right?
"react": "17.0.1", "react-dom": "17.0.1",
Hi, I am enjoying this package, works perfect so far. Thank you.
Just come here to ask you if you have a best way to redirect to another page if the user is not authenticated. For example lets say "dashboard" it should redirect if not logged in.
This is my page
import React, { Component } from 'react'
import { Default } from '@/components/templates/Default'
class Dashboard extends Component {
render() {
return (
<>
<Default description="Dashboard Description" title="User's Dashboard">
<div className="user-area-all-style sign-up-area pt-100 bg-black">
Dashboard Content
</div>
</Default>
</>
)
}
}
export default Dashboard
I have a fresh application using NextJS, and my implementation looks like this:
function MyApp({ Component, pageProps }) {
return (
<Sanctum config={sanctumConfig} checkOnInit>
<Component {...pageProps} />
</Sanctum>
)
}
And in my network tab, on every page load loads my user_object_route twice, once successfully, and once with a 401 error. The code above is my only react-sanctum code added, there's nothing else going on. Did I do something wrong?
I'm using, in a project, react-sanctum
and it feels great. In the meanwhile, callbacks like onAuthenticated()
and getUser()
on Sanctum
and withSanctum
could be of great use.
<Sanctum
checkOnInit
config={}
onAuthenticated={(user,....) => {}}
>
<SubAppComponents />
</Sanctum>
const SubAppComponents = ({user, getUser, authenticated } ) => {
// refresh user object
if (condition) getUser()
return .....
}
export default withSanctum(SubAppComponents)
What do you think?
Is there any way for the user data to be fetched before the page loads? I've got the users name on the homepage and its briefly undefined until the page finishes loading.
I am looking to sign in and authenticate my users with a Laravel Sanctum token and would like to get user data into my react native app once the user is logged in. is it possible to achieve this in react native, with your package.
Hi !
The backend implementation works fine as the login route does output in the console the correct answer from the server with the user variable
But when I use signIn, it does give success but in 'then' I have User:false
any idea ?
I'm absolutely sure that I'm missing something, but I just can't figure it out. Here's my login:
const LoginButton = () => {
const { authenticated, user, signIn } = useSanctum();
const handleLogin = () => {
signIn(userEmail.current.value, userPassword.current.value, rememberMe)
.then(() => (
<MDAlert color="error" dismissible>
{alertContent("Login Success", "You're logged in!")}
</MDAlert>
))
.catch((result) => (
<MDAlert color="error" dismissible>
{alertContent("Login Error", result.message)}
</MDAlert>
));
};
if (authenticated === true) {
return <h1>Welcome, {user.name}</h1>;
}
return <MDButton onClick={handleLogin}>Sign in</MDButton>;
};
Here's my backend login method:
public function login(Request $request)
{
$fields = $request->validate([
'email' => 'required|string',
'password' => 'required|string',
]);
// Check email
$user = User::where('email', $fields['email'])->first();
// Check password
if (!$user || !Hash::check($fields['password'], $user->password)) {
return response([
'message' => 'Unable to find an account with that username/password combination.',
], 401);
}
$token = $user->createToken('budget-api')->plainTextToken;
$response = [
'user' => $user,
'token' => $token,
];
return response($response, 201);
}
I'm noticing 2 calls to my api/login
route: a POST and an OPTIONS. However, when I do my api/user
call, I get a 401
back. Any help would be appreciated.
Hi,
I'm building a mobile app and I would like to use this package, but it looks like it's only to be used with csrfCookie. We cannot make it works for Sanctum Token ?
hi
please show starter kit with sanctum auth
backend
frontend
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.