Skip to content

Commit 96c6b18

Browse files
authored
Merge pull request #2 from SurajShettigar/master
Add user authorization. Add fetching of posts, comments, users. Update README.md
2 parents 63e80b6 + 3ea4dec commit 96c6b18

21 files changed

Lines changed: 1390 additions & 352 deletions

.idea/workspace.xml

Lines changed: 209 additions & 146 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 88 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,93 @@
1-
# flutter_wordpress
1+
# Flutter Wordpress
22

3-
Flutter Wordpress API
3+
This library uses [WordPress REST API V2](https://developer.wordpress.org/rest-api/) to provide a way for your application to interact with your WordPress website.
44

55
## Requirements
6-
- A Wordpress site using V2 REST API https://developer.wordpress.org/rest-api/
7-
- JWT Authentication for WP REST API V2 https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/
8-
- Flutter 1.0 https://flutter.io/docs/get-started/install
6+
For authentication and usage of administrator level REST APIs, you need to use either of the two popular authentication plugins in your WordPress site:
7+
1. [Application Passwords](https://wordpress.org/plugins/application-passwords/)
8+
2. [JWT Authentication for WP REST API](https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/)
9+
10+
## Getting Started
11+
12+
### 1. Import library
13+
14+
```dart
15+
import 'package:flutter_wordpress/flutter_wordpress.dart' as wp;
16+
```
17+
18+
### 2. Instantiate WordPress class
19+
20+
```dart
21+
wp.WordPress wordPress;
22+
23+
// adminName and adminKey is needed only for admin level APIs
24+
wordPress = wp.WordPress(
25+
baseUrl: 'http://localhost',
26+
authenticator: wp.WordPressAuthenticator.ApplicationPasswords,
27+
adminName: '',
28+
adminKey: '',
29+
);
30+
```
31+
32+
### 3. Authenticate User
33+
34+
```dart
35+
Future<wp.User> response = wordPress.authenticateUser(
36+
username: 'username',
37+
password: 'password',
38+
);
39+
40+
response.then((user) {
41+
print(user.toString());
42+
}).catchError((err) {
43+
print(err.toString());
44+
});
45+
```
46+
47+
### 4. Fetch Posts
48+
49+
```dart
50+
Future<List<wp.Post>> posts = wordPress.fetchPosts(
51+
params: wp.ParamsPostList(
52+
context: wp.WordPressContext.view,
53+
pageNum: 1,
54+
perPage: 20,
55+
order: wp.Order.desc,
56+
orderBy: wp.PostsOrderBy.date,
57+
),
58+
);
59+
```
60+
61+
### 5. Fetch Users
62+
63+
```dart
64+
Future<List<wp.User>> users = wordPress.fetchUsers(
65+
params: wp.ParamsUserList(
66+
context: wp.WordPressContext.view,
67+
pageNum: 1,
68+
perPage: 30,
69+
order: wp.Order.asc,
70+
orderBy: wp.UsersOrderBy.name,
71+
role: wp.UserRole.subscriber,
72+
),
73+
);
74+
```
75+
76+
### 6. Fetch Comments
77+
78+
```dart
79+
Future<List<wp.Comment>> comments = wordPress.fetchComments(
80+
params: wp.ParamsCommentList(
81+
context: wp.WordPressContext.view,
82+
pageNum: 1,
83+
perPage: 30,
84+
includePostIDs: [1],
85+
),
86+
);
87+
```
88+
89+
## Future Work
90+
1. Implementing OAuth 2.0 authentication.
91+
992

1093

example/lib/main.dart

Lines changed: 69 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -51,59 +51,109 @@ class PostsBuilder extends StatefulWidget {
5151

5252
class PostsBuilderState extends State<PostsBuilder> {
5353
wp.WordPress wordPress;
54-
Future<List<wp.Posts>> posts;
55-
Future<List<wp.Users>> users;
54+
Future<List<wp.Post>> posts;
55+
Future<List<wp.User>> users;
5656

5757
@override
5858
void initState() {
5959
super.initState();
6060

61-
wordPress = wp.WordPress(
62-
'https://wordpress.dsoft.website', wp.WordpressContext.view);
61+
try {
62+
wordPress = wp.WordPress(
63+
baseUrl: 'http://192.168.6.165',
64+
authenticator: wp.WordPressAuthenticator.ApplicationPasswords,
65+
adminName: 'admin',
66+
adminKey: 'EOjD JsYA hKfM RHNI vufW hyUX',
67+
);
68+
} catch (err) {
69+
print(err.toString());
70+
}
71+
72+
/* Future<wp.User> response = wordPress.authenticateUser(
73+
username: 'username',
74+
password: 'password',
75+
);
6376
64-
Future<wp.AuthResponse> auth = wordPress.authenticateUser(
65-
username: 'admin ', password: 'mypassword@123');
77+
response.then((user) {
78+
print(user.toString());
79+
}).catchError((err) {
80+
print(err.toString());
81+
});*/
82+
83+
Future<List<wp.User>> users = wordPress.fetchUsers(
84+
params: wp.ParamsUserList(
85+
context: wp.WordPressContext.view,
86+
pageNum: 1,
87+
perPage: 30,
88+
order: wp.Order.asc,
89+
orderBy: wp.UsersOrderBy.name,
90+
),
91+
);
6692

67-
auth.then((response) {
68-
fetchPosts();
93+
users.then((response) {
94+
print(response);
6995
}).catchError((err) {
70-
print(err.message);
96+
print(err.toString());
7197
});
7298

99+
Future<List<wp.Comment>> comments = wordPress.fetchComments(
100+
params: wp.ParamsCommentList(
101+
context: wp.WordPressContext.view,
102+
pageNum: 1,
103+
perPage: 30,
104+
),
105+
);
106+
107+
comments.then((response) {
108+
print(response);
109+
}).catchError((err) {
110+
print(err.toString());
111+
});
73112
}
74113

75-
void fetchPosts()
76-
{
114+
void fetchPosts() {
77115
setState(() {
78-
posts = wordPress.fetchPosts();
116+
posts = wordPress.fetchPosts(params: wp.ParamsPostList());
79117
});
80118
}
81119

82-
void fetchUsers()
83-
{
120+
void fetchUsers() {
84121
setState(() {
85-
users = wordPress.fetchUsers();
122+
users = wordPress.fetchUsers(params: wp.ParamsUserList());
86123
});
87124
}
88125

89126
@override
90127
Widget build(BuildContext context) {
91-
return FutureBuilder<List<wp.Posts>>(
128+
return FutureBuilder<List<wp.Post>>(
92129
future: posts,
93130
builder: (context, snapshot) {
94131
if (snapshot.hasData) {
95132
return ListView.separated(
96133
itemBuilder: (context, i) {
97-
return Text(snapshot.data[i].title.rendered);
134+
return Column(
135+
crossAxisAlignment: CrossAxisAlignment.start,
136+
children: <Widget>[
137+
Text(
138+
snapshot.data[i].title.rendered,
139+
style: Theme.of(context).textTheme.title,
140+
),
141+
Text(
142+
snapshot.data[i].content.rendered,
143+
),
144+
],
145+
);
98146
},
99147
separatorBuilder: (context, i) {
100148
return Divider();
101149
},
102150
itemCount: snapshot.data.length,
103151
);
104152
} else if (snapshot.hasError) {
105-
wp.WordpressError err = snapshot.error as wp.WordpressError;
106-
return Text(err.message);
153+
return Text(
154+
snapshot.error.toString(),
155+
style: TextStyle(color: Colors.red),
156+
);
107157
}
108158
return CircularProgressIndicator();
109159
},

lib/constants.dart

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
const URL_WP_BASE = '/wp-json/wp/v2';
2+
const URL_JWT_BASE = '/wp-json/jwt-auth/v1';
3+
4+
const URL_JWT_TOKEN = '$URL_JWT_BASE/token';
5+
const URL_JWT_TOKEN_VALIDATE = '$URL_JWT_BASE/token/validate';
6+
7+
const URL_POSTS = '$URL_WP_BASE/posts';
8+
const URL_USERS = '$URL_WP_BASE/users';
9+
const URL_COMMENTS = '$URL_WP_BASE/comments';
10+
11+
enum WordPressAuthenticator {
12+
JWT,
13+
ApplicationPasswords,
14+
}
15+
enum WordPressContext { view, embed, edit }
16+
17+
enum Order {
18+
asc,
19+
desc,
20+
}
21+
22+
enum PostsOrderBy {
23+
author,
24+
date,
25+
id,
26+
include,
27+
modified,
28+
parent,
29+
relevance,
30+
slug,
31+
title,
32+
}
33+
enum PostStatus {
34+
publish,
35+
future,
36+
draft,
37+
pending,
38+
private,
39+
}
40+
enum PostCommentStatus {
41+
open,
42+
closed,
43+
}
44+
enum PostPingStatus {
45+
open,
46+
closed,
47+
}
48+
enum ObjectFormat {
49+
standard,
50+
aside,
51+
chat,
52+
gallery,
53+
link,
54+
image,
55+
quote,
56+
status,
57+
video,
58+
audio,
59+
}
60+
61+
enum UsersOrderBy {
62+
id,
63+
include,
64+
name,
65+
registered_date,
66+
slug,
67+
email,
68+
url,
69+
}
70+
enum UserRole {
71+
subscriber,
72+
contributor,
73+
author,
74+
editor,
75+
administrator,
76+
}
77+
78+
enum CommentsOrderBy {
79+
date,
80+
date_gmt,
81+
id,
82+
include,
83+
post,
84+
parent,
85+
type,
86+
}
87+
enum CommentStatus {
88+
all,
89+
approve,
90+
hold,
91+
spam,
92+
trash,
93+
}
94+
enum CommentType {
95+
comment,
96+
//TODO: Add all comment types
97+
}
98+
99+
/// Converts an enum string to enum value name.
100+
String enumStringToName(String enumString) {
101+
return enumString.split('.')[1];
102+
}
103+
104+
/// Formats a list of [items] to a comma(,) separated string to pass it as a
105+
/// URL parameter.
106+
String listToUrlString<T>(List<T> items) {
107+
if (items == null || items.length == 0) return '';
108+
109+
return items.join(',');
110+
}
111+
112+
/// Formats a [Map] of parameters to a string of URL friendly parameters.
113+
String constructUrlParams(Map<String, String> params) {
114+
StringBuffer p = new StringBuffer('/?');
115+
params.forEach((key, value) {
116+
if (value != '') {
117+
p.write('$key=$value');
118+
p.write('&');
119+
}
120+
});
121+
return p.toString();
122+
}

0 commit comments

Comments
 (0)